2011-04-29 37 views
0

嘿,我有一個simpleXMLElement文檔,其中包含一組數據以處理藝術家的相冊。PHP中的XML循環語句

下面是XML

[2] => SimpleXMLElement Object 
        (
         [@attributes] => Array 
          (
           [num] => 3 
           [type] => artist 
          ) 

         [title] => DJ Tiësto 
         [uri] => http://www.discogs.com/artist/DJ+Ti%C3%ABsto 
         [summary] => DJ Tiësto Tijs Michiel Verwest Dutch trance DJ & producer. 

在這個XML文檔的提取物有多種不同類型的藝術家,從信息到專輯的標題信息。我想提取這些數據的某些部分並將它們回顯出來。例如,我想提取具有爲藝術家定義的[類型]的數組條目的摘要。我猜我會使用通過所有條目的foreach循環,並檢查這是否屬實?這是正確的方式去解決它。

我爲我的困惑解釋道歉

---- ----編輯

繼承人的PHP代碼,抓住數據 -

<?php 
$curl = curl_init(); 
curl_setopt($curl, CURLOPT_URL, "http://www.discogs.com/search?type=all&" . 
"q=DJ+Tiësto&" . 
"f=xml&" . 
"api_key=<key>"); 
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($curl, CURLOPT_ENCODING, "gzip"); 
$result = curl_exec($curl); 
curl_close($curl); 


    $xmlmusic = new SimpleXMLElement($result,NULL,true); 

foreach ($xmlmusic as $xm) 
    { 
    $attrs = $xm->attributes(); 
    if($attrs["type"] == "title") 
     echo $xm->summary."\n"; 
    } 

>

+1

你應該先嚐試一下,節省一些時間。 – Galen 2011-04-29 20:26:15

+0

[一個簡單的程序到xml文件的CRUD節點和節點值]的可能的重複(http://stackoverflow.com/questions/4906073/a-simple-program-to-crud-node-and-node-values-of -xml文件) – Gordon 2011-04-29 20:29:23

+0

可能的重複[如何訪問元素屬性與SimpleXml](http://stackoverflow.com/questions/4625045/how-to-access-element-attributes-with-simplexml) – Gordon 2011-04-29 20:31:18

回答

0

如果你需要得到屬性,你可以使用下面的例子

$Attributes = $Node->attributes();

1

那麼,雖然這裏可能的重複是一個基於你的文件的非常簡單的例子。

我想你有這樣的事情:

<music> 
    <dj num="3" type="artist"> 
     <title>DJ Tiesto</title> 
     <uri>http://www.discogs.com/artist/DJ+Ti%C3%ABsto</uri> 
     <summary>DJ Tiësto Tijs Michiel Verwest Dutch trance DJ producer.</summary> 
    </dj> 
    <dj num="4" type="artist"> 
     <title>title</title> 
     <uri>url</uri> 
     <summary>summary</summary> 
    </dj> 

爲了提取摘要,其中屬性類型是「標題」,如你要求,你需要的東西是這樣的:

<?php 
    $result = file_get_contents("http://www.discogs.com/search?type=all&" . 
       "q=DJ+Tiësto&" . 
       "f=xml&" . 
       "api_key=<key>"); 

    $xmlmusic = new SimpleXMLElement($result, NULL, false); 

    //print_r($xmlmusic); 

    foreach ($xmlmusic as $xm) 
    { 
     $attrs = $xm->attributes(); 
     if($attrs["type"] == "title") 
      echo $xm->summary."\n"; 
    } 
?> 

爲自己測試,它的工作原理。

+0

您好nunaxe您的答案似乎是在正確的路線,我試圖實現你的代碼。我已經用完整的PHP代碼編輯了我的問題。但使用cURL但它返回一個錯誤:致命錯誤:未收集的異常'異常'與消息'字符串不能被解析爲XML的行上,您將XML加載到變量xmlmusic – DIM3NSION 2011-04-29 21:19:22

+0

這意味着simplexml有解析問題XML。你可以嘗試輸出$結果並驗證它是有效的XML嗎? – DaOgre 2011-04-29 21:24:50

+0

按照DaOgre的建議。做'print_r($ result)'。由於禁止入站信息檢索,在我的系統對cURL和simplexml_load_file()的調用不能按預期工作。 – nunaxe 2011-04-29 21:50:22