views:

371

answers:

4

I'm learning how to parse XML with PHP's simple XML. My code is:

<?php
$xmlSource = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>    <Document xmlns=\"http://www.apple.com/itms/\" artistId=\"329313804\" browsePath=\"/36/6407\" genreId=\"6507\">    <iTunes> myApp </iTunes> </Document>";

$xml = new SimpleXMLElement($xmlSource);

$results = $xml->xpath("/Document/iTunes");
foreach ($results as $result){
 echo $result.PHP_EOL;  
}

print_r($result);
?>

When this runs it returns a blank screen, with no errors. If I remove all the attributes from the Document tag, it returns :

myApp SimpleXMLElement Object ( [0] => myApp )

Which is the expected result.

What am I doing wrong? Note that I don't have control over the XML source, since it's coming from Apple.

A: 

This line:

print_r($result);

is outside the foreach loop. Maybe you should try

print_r($results);

instead.

sanders
A: 

Seems if you use the wildcard (//) on xpath it will work. Also, not sure why but if you remove the namespace attribute (xmlns) from the Document element, your current code will work. Maybe because a prefix isn't defined? Anyway, following should work:

$results = $xml->xpath("//iTunes");
foreach ($results as $result){
 echo $result.PHP_EOL;  
}
Aaron W.
+3  A: 

Your xml contains a default namespace. In order to get your xpath query to work you need to register this namespace, and use the namespace prefix on every xpath element you are querying (as long as these elements all fall under the same namespace, which they do in your example):

$xml = new SimpleXMLElement( $xmlSource );

// register the namespace with some prefix, in this case 'a'
$xml->registerXPathNamespace( 'a', 'http://www.apple.com/itms/' );

// then use this prefix 'a:' for every node you are querying
$results = $xml->xpath( '/a:Document/a:iTunes' );

foreach( $results as $result )
{
    echo $result . PHP_EOL; 
}
fireeyedboy
+1  A: 

For the part about the default namespace, read fireeyedboy's answer. As mentionned, you need to register a namespace if you want to use XPath on nodes that are in the default namespace.

However, if you don't use xpath(), SimpleXML has its own magic that selects the default namespace automagically.

$xmlSource = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>    <Document xmlns=\"http://www.apple.com/itms/\" artistId=\"329313804\" browsePath=\"/36/6407\" genreId=\"6507\">    <iTunes> myApp </iTunes> </Document>";

$Document = new SimpleXMLElement($xmlSource);

foreach ($Document->iTunes as $iTunes)
{
    echo $iTunes, PHP_EOL;
}
Josh Davis
Fantastic! Can you point me to the documentation explaining this feature in detail?
SooDesuNe
Well, that's the thing: to the best of my knowledge there's no doc about how default namespaces are handled.
Josh Davis