使用PHP SimpleXml解析XML文档的问题

时间:2011-12-13 23:30:16

标签: php xml api parsing simplexml

之前我曾使用xpath处理XML元素,但是我很难为这个特定的XML获取正确的语法。

我正在尝试解析监护人API响应。样品回复:

<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>

这是我第一次尝试用PHP编写代码(我使用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\">";
  }

它没有检索任何内容,我的代码中是否有任何缺陷?

1 个答案:

答案 0 :(得分:0)

<?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/>";
    }
?>