Parsing XML Data with PHP Namespaces

I'm trying to work with this XML feed that uses namespaces and I can't seem to get past the colon in the tags. This is what the XML stream looks like:

<r25:events pubdate="2010-05-19T13:58:08-04:00">
<r25:event xl:href="event.xml?event_id=328" id="BRJDMzI4" crc="00000022" status="est">
 <r25:event_id>328</r25:event_id>
 <r25:event_name>Testing 09/2005-08/2006</r25:event_name>
 <r25:alien_uid/>
 <r25:event_priority>0</r25:event_priority>
 <r25:event_type_id xl:href="evtype.xml?type_id=105">105</r25:event_type_id>
 <r25:event_type_name>CABINET</r25:event_type_name>
 <r25:node_type>C</r25:node_type>
 <r25:node_type_name>cabinet</r25:node_type_name>
 <r25:state>1</r25:state>
 <r25:state_name>Tentative</r25:state_name>
 <r25:event_locator>2005-AAAAMQ</r25:event_locator>
 <r25:event_title/>
 <r25:favorite>F</r25:favorite>
 <r25:organization_id/>
 <r25:organization_name/>
 <r25:parent_id/>
 <r25:cabinet_id xl:href="event.xml?event_id=328">328</r25:cabinet_id>
 <r25:cabinet_name>cabinet 09/2005-08/2006</r25:cabinet_name>
 <r25:start_date>2005-09-01</r25:start_date>
 <r25:end_date>2006-08-31</r25:end_date>
 <r25:registration_url/>
 <r25:last_mod_dt>2008-02-27T14:22:43-05:00</r25:last_mod_dt>
 <r25:last_mod_user>abc00296004</r25:last_mod_user>
</r25:event>
</r25:events>

      

And this is what I use for the code - I will try to throw them into a bunch of arrays where I can format the output, but I want:

<?php

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://somedomain.com/blah.xml");
curl_setopt ($ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml"));
curl_setopt($ch, CURLOPT_USERPWD, "username:password");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);

$xml = new SimpleXmlElement($output);
foreach ($xml->events->event as $entry){
  $dc = $entry->children('http://www.collegenet.com/r25');
  echo $entry->event_name . "<br />";
  echo $entry->event_id . "<br /><br />";
}

      

+2


a source to share


3 answers


It turned out that the problem was with the XML feed, not the code:

The XML root is missing this line:



<r25:events xmlns:r25="http://www.collegenet.com/r25" xmlns:xl="http://www.w3.org/1999/xlink" pubdate="2010-05-19T13:58:08-04:00">

      

Thanks for the help.

+1


a source


"All Sorts of Errors" is not a useful description; what errors are you actually getting?

You must provide the object with a namespace variant, for example:



$xml = new SimpleXmlElement($output, null, false, $ns = 'r25');

      

See the manual .

-1


a source


Alternatively, since r25 is the only namespace in use and therefore not particularly useful, I just run

$xml = preg_replace('/r25:/','',$xml);

      

And that removes the namespace. Then you can navigate easily with simplexml like in your example.

-2


a source







All Articles