使用 PHP 从 XML 文件中获取嵌套标记值


get nested tag value from xml file using php

我有一个特殊格式的 XML 文件,例如,如果我想获取每个 dict 标签的旋转值,我如何从中获取特定的标签值。 如您所见,每个字典的旋转值都嵌套在嵌套在dist 标签中的数组标签中。请指出我正确的方向

<?xml version="1.0" encoding="UTF-8"?>
<pu version="1.0">
  <dict>
    <key>ID</key>
    <string>C0AC8773-CEE6-4A12-9C69-320A1BDB7255</string>
    <key>Items</key>
    <array>
      <dict>
        <key>opacity</key>
        <real>1</real>
        <key>Thickness</key>
        <real>0</real>
        <key>repeat</key>
        <false/>
        <key>rotation</key>
        <real>90</real>
      </dict>
      <dict>
        <key>opacity</key>
        <real>1</real>
        <key>Thickness</key>
        <real>0</real>
        <key>repeat</key>
        <false/>
        <key>rotation</key>
        <real>180</real>
      </dict>
      <dict>
        <key>opacity</key>
        <real>1</real>
        <key>Thickness</key>
        <real>0</real>
        <key>repeat</key>
        <false/>
        <key>rotation</key>
        <real>270</real>
      </dict>
    </array>
  </dict>
</pu>

这是我到目前为止尝试过的

$dom = new DOMDocument;
$dom->load($path);
$array = $dom->getElementsByTagName('array');
foreach($array as $key)
{
   print_r($key);
}

这将打印数组标签内的所有标签,但我只想要旋转值

将这些 XML 数据

粘贴到文件中,例如yourxmlfile.xml并使用simplexml_load_file()来解析 XML 数据。使用foreach您可以像这样循环。

<?php
$xml = simplexml_load_file('yourxmlfile.xml');
foreach ($xml->dict->array->dict as $tag)
{
    if($tag[0]->key[3]=="rotation")
    {
        echo $tag[0]->real[2]."<br>";
    }
}

OUTPUT :

90
180
270

正如另一个答案所说,key/(value)"配对"是奇怪的。但是,您也可以为此使用 xPath:

$xml = new SimpleXMLElement($string);
$result = $xml->xpath("dict/array/dict/key[text()='rotation']/following-sibling::real");
while(list( , $node) = each($result)) {
    echo 'dict/array/dict/rotation: ',$node,"'n";
}

http://codepad.org/ib4NiBBz

这给了:

dict/array/dict/rotation: 90
dict/array/dict/rotation: 180
dict/array/dict/rotation: 270

http://www.php.net/manual/en/simplexmlelement.xpath.php

您可以使用 XPath 表达式来实现它:

$dom = new DOMDocument;
$dom->loadXML($xml);    
$xpath = new DOMXPath($dom);
$nodes = $xpath->query("//*[text()='rotation']/following-sibling::real/text()");
foreach ($nodes as $node) {
    echo $node->nodeValue, PHP_EOL;
}

XPath 表达式表示:查找所有<real>标签,后跟任何具有节点值rotation的标签,并获取其节点值。XPath 表达式允许您更好地控制标记。您可以根据需要调整表达式。

输出:

90
180
270

在线演示