Parsing XML with PHP's simpleXML

前端 未结 5 1450
北恋
北恋 2020-12-11 10:23

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



        
相关标签:
5条回答
  • 2020-12-11 10:52

    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;
    }
    
    0 讨论(0)
  • 2020-12-11 11:03

    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;  
    }
    
    0 讨论(0)
  • 2020-12-11 11:05

    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; 
    }
    
    0 讨论(0)
  • 2020-12-11 11:05

    This line:

    print_r($result);
    

    is outside the foreach loop. Maybe you should try

    print_r($results);
    

    instead.

    0 讨论(0)
  • 2020-12-11 11:09

    this is general example

    foreach ($library->children() as $child)
    {
       echo $child->getName() . ":\n";
       foreach ($child->attributes() as $attr)
       {
        echo  $attr->getName() . ': ' . $attr . "\n";
      }
    foreach ($child->children() as $subchild)
    {
        echo   $subchild->getName() . ': ' . $subchild . "\n";
    }
       echo "\n";
    }
    

    for more information check this : http://www.yasha.co/XML/how-to-parse-xml-with-php-simplexml-DOM-Xpath/article-1.html

    0 讨论(0)
提交回复
热议问题