2011-12-13 22 views
0

以前はXML要素を処理するためにxpathを使用しましたが、この特定のXMLの構文を正しく取得するのには苦労しています。PHP SimpleXmlを使用したXML文書の解析のトラブルシューティング

私はガーディアンAPIの応答を解析しようとしています。サンプル応答:

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

それは何も取得しません、私のコードのいずれかの欠陥がある:

<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でそれをコーディングしてみてください、私の最初のでしょうか?

+0

2つのものが飛び出します。最初のコード行では、XML要素$ news_itemsを作成しますが、別の行でクエリを実行しています。行1を削除し、行3を$ news_items = new SimpleXmlElement($ result) - > xpath( '/ response/results/tag')に変更します。第2に、xpathはタグ要素を取得せず、/ response/results /タグを指定して取得します –

答えて

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