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、ランク、説明を取得しますか?上記のアイテムは3つだけ投稿しました。実際には約50個あります。

4

3 に答える 3

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 に答える
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 に答える