views:

2235

answers:

3

I have this as xml:

<event:event>
         <event:sessionKey></event:sessionKey>
         <event:sessionName>Learn QB in Minutes</event:sessionName>
         <event:sessionType>9</event:sessionType>
         <event:hostWebExID></event:hostWebExID>
         <event:startDate>02/12/2009</event:startDate>
         <event:endDate>02/12/2009</event:endDate>
         <event:timeZoneID>11</event:timeZoneID>
         <event:duration>30</event:duration>
         <event:description></event:description>
         <event:status>NOT_INPROGRESS</event:status>
         <event:panelists></event:panelists>
         <event:listStatus>PUBLIC</event:listStatus>
      </event:event>

How can I loop through all of the event:event nodes and display, for example, all of the event:SessionKey's?

This does not work:

$xml = new SimpleXMLElement($r);
$xml->registerXPathNamespace('e', 'http://www.webex.com/schemas/2002/06/service/event');

foreach($xml->xpath('//e:event') as $event) {
 var_export($event->xpath('//e:sessionKey'));
}
A: 

I could be wrong but I don't think XML with the colon symbol like SOAP can be parsed properly using SimpleXMLElement.

I'm sure there's a more elegant way of doing this but I usually read the file contents into a variable using file_get_contents() then replace/remove the colons then send it to SimpleXMLElement.

givp
Actually, there is some support for namespacing: http://us.php.net/manual/en/function.simplexml-element-registerXPathNamespace.phpAnd I'm aware that namespaces can be removed like so:$namespaceFree = preg_replace(’/([<<\/])([a-z0-9]+):/i’,'$1$2′,$xml);I'm just looking for a better solution.
A: 

it does work without registerXPathNamespace and the full namespace prefix in the xpath queries:

$xml = new SimpleXMLElement($r);

foreach($xml->xpath('//event:event') as $event) {
 var_export($event->xpath('event:sessionKey'));
}
ax
+3  A: 

You have to register the namespace for each simpleXMLElement object you use.

$xml = new SimpleXMLElement($r);
$xml->registerXPathNamespace('e', 'http://www.webex.com/schemas/2002/06/service/event');

foreach($xml->xpath('//e:event') as $event) {
    $event->registerXPathNamespace('e', 'http://www.webex.com/schemas/2002/06/service/event');
    var_export($event->xpath('//e:sessionKey'));
}

The namespace should also be declared somewhere in the xml file.

<event:event xmlns:event="http://www.webex.com/schemas/2002/06/service/event"&gt;
...

The method ax described works too. You can skip the registerXPathNamespace if you know the xml file will always use the same prefix.

mcrumley