0

对,所以这是我使用 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、rank 和解释的呢?我只发布了上面的 3 个项目。实际上大约有50个。

4

3 回答 3

0

试试这个教程:

http://www.phpro.org/tutorials/Introduction-To-SimpleXML-With-PHP.html

于 2012-06-29T17:09:44.657 回答
0
foreach($xml->xpath('/results')->children() as $child)
{
   $mystuff = $child->getChildren();
   $id = $mystuff[0];
   $rank = $mystuff[1];
   $explanation = $mystuff[2];
}

类似的东西。请参阅SimpleXMLElement 对象的 PHP 文档

于 2012-06-29T17:10:31.397 回答
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;
        }
    }
}
于 2012-06-29T17:43:27.300 回答