2012-06-29 110 views
0

對,所以這是我第一天使用XML。我沒有創建XML,有人給我發送一個URL,我需要用PHP做些什麼。這是XML結構的樣子:從XML訪問數據

<response> 
<query id="1"> 
<results> 
    <item> 
     <id>GZ7w39jpqwo</id> 
     <rank>1</rank> 
     <explanation>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla a massa lectus, sed convallis sapien. Curabitur sem mauris, ullamcorper ut. </explanation> 
    </item> 
    <item> 
     <id>hfMNRUAwLVM</id> 
     <rank>2</rank> 
     <explanation>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla a massa lectus, sed convallis sapien. Curabitur sem mauris, ullamcorper ut. </explanation> 
    </item> 
    <item> 
     <id>I_cxElavpS8</id> 
     <rank>3</rank> 
     <explanation>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla a massa lectus, sed convallis sapien. Curabitur sem mauris, ullamcorper ut. </explanation> 
    </item> 
</results> 
</query> 
</response> 

所以,是的,這是我到目前爲止已經想通了......

$url = "http://www.MyURL.blah"; 

$string = file_get_contents($url); 

$xml = simplexml_load_string($string); 

echo $xml->getName(); 

這呼應了字的迴應「。耶,走吧!那麼現在你到底是如何得到每件物品的ID,等級和解釋?我只在上面發佈了3個項目。有需要實際約50

+0

爲什麼不這項工作:$字符串=的file_get_contents($網址); $ xml = simplexml_load_string($ string); foreach($ xml as $ row) { echo $ row-> rank。 '
'; } – AzzyDude

回答

0

這個例子可以幫助你,它使用DOMDocument。

$document = new DOMDocument(); //Creates a new DOM Document (used to process XML) 
$document->loadXML($fileContents); //Load the XML file from an string 
$resultsNode = $document->getElementsByTagName("results")->item(0); //Get the node with the results tag 
foreach($resultsNode->childNodes as $itemNode) //Get each child node (item) and process it 
{ 
    foreach($itemNode->childNodes as $unknownNode) //Get each child node of item and process it 
    { 
     if($unknownNode->nodeName == "id") //Check if it's the dessired node 
     { 
      $this->id = $unknownNode->value; //Assign the value of the node to a variable 
     } 
     if($unknownNode->nodeName == "rank") 
     { 
      $this->rank = $unknownNode->value; 
     } 
     if($unknownNode->nodeName == "explanation") 
     { 
      $this->explanation = $unknownNode->value; 
     } 
    } 
} 
+0

...我不知道這段代碼是怎麼回事。 – AzzyDude

+0

@AzzyDude更正以符合您的要求 – Rafael

0
foreach($xml->xpath('/results')->children() as $child) 
{ 
    $mystuff = $child->getChildren(); 
    $id = $mystuff[0]; 
    $rank = $mystuff[1]; 
    $explanation = $mystuff[2]; 
} 

類似的東西。看到PHP文檔的SimpleXMLElement object