是的,所以这是我使用XML的第一天。我不是在创建XML,有人给我发了一个URL,我需要用PHP做一些事情。这就是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 :(得分:0)
答案 1 :(得分:0)
foreach($xml->xpath('/results')->children() as $child)
{
$mystuff = $child->getChildren();
$id = $mystuff[0];
$rank = $mystuff[1];
$explanation = $mystuff[2];
}
这样的事情。请参阅SimpleXMLElement object
的PHP文档答案 2 :(得分: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;
}
}
}