简体   繁体   中英

Troubleshooting parsing of XML document using PHP SimpleXml

I've used xpath to process XML element before, however I'm struggling to get the syntax right for this particular XML.

I'm trying to parse a guardian API response. Sample response:

<response user-tier="approved" current-page="1" start-index="1" page-size="10" pages="1" total="10" status="ok">
<results>
<tag type="series" web-title="Cycling" section-name="Life and style"   id="lifeandstyle/series/cycling" api-   url="http://content.guardianapis.com/lifeandstyle/series/cycling" section-id="lifeandstyle" web-  url="http://www.guardian.co.uk/lifeandstyle/series/cycling"/>
 <tag type="keyword" web-title="Cycling" section-name="Sport" id="sport/cycling" api- url="http://content.guardianapis.com/sport/cycling" section-id="sport" web- url="http://www.guardian.co.uk/sport/cycling"/>
 <tag type="keyword" web-title="Cycling" section-name="Life and style"   id="lifeandstyle/cycling" api-url="http://content.guardianapis.com/lifeandstyle/cycling"    section-id="lifeandstyle" web-url="http://www.guardian.co.uk/lifeandstyle/cycling"/>
 <results>
 <response>

Here is my first try coding it in PHP (I've connected using cURL):

 $news_items = new SimpleXMLElement($result); //loads the result of the cURL into a simpleXML response 

 $news_items = $guardian_response->xpath('results'); 

 foreach ($news_items as $item) { //for each statement every entry will load the news_item  and the web_url for the document
    $item_block = "<p class=\"web_title\">";
$item_block = "<p class=\"web_url\">";
  }

It doesn't retrieve anything, is there any flaws in my code?

<?php
    function getAttribute($object, $attribute) { 
        foreach($object->attributes() as $a => $b) { 
            if ($a == $attribute) { $return = $b; } 
        } 
        if($return) { return $return; } 
    } 

    try {
        $xml = simplexml_load_file( "parse.xml" );

        /* Pay attention to the XPath, include all parents */
        $result = $xml->xpath('/response/results/tag');

        while(list( , $node) = each($result)) {
             echo getAttribute( $node, "type" );
        }

    } catch( Exception $e ) {
        echo "Exception on line ".$e->getLine()." of file ".$e->getFile()." : ".$e->getMessage()."<br/>";
    }
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM