2011-12-13 56 views
0

我之前使用過xpath來處理XML元素,但是我正努力爲這個特定的XML獲取正確的語法。使用PHP SimpleXml解析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(我一直在使用捲曲連接):

$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\">"; 
    } 

它不獲取任何,有沒有在我的代碼的任何缺陷?

+0

2件東西跳出來。首先在第一行代碼中,創建一個XML元素$ news_items,但是您正在對另一個元素運行查詢。刪除第1行,並將第3行更改爲$ news_items = new SimpleXmlElement($ result) - > xpath('/ response/results/tag')。其次,你的xpath不會得到任何標籤元素,指定/ response/results/tag來獲得它們 – 2011-12-14 15:15:32

回答

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