使用PHP按ID获取XML元素


Get XML element by ID with PHP

我在让PHP读取XML文档时遇到了一些困难。我试图根据我选择的catid来回显每个节点的内容。

XML:text.XML

<root>
  <category catid='1'>
    <text id='TXT1'><![CDATA[ Lorem Ipsum ]]></text>
    <text id='TXT2'><![CDATA[ Lorem Ipsum ]]></text>
    <text id='TXT3'><![CDATA[ Lorem Ipsum ]]></text>
  </category>
  <category catid='2'>
    <text id='TXT1'><![CDATA[ Lorem Ipsum ]]></text>
    <text id='TXT2'><![CDATA[ Lorem Ipsum ]]></text>
    <text id='TXT3'><![CDATA[ Lorem Ipsum ]]></text>
  </category>
</root>

PHP:

<?php  
$xml = simplexml_load_file('/path/to/text.xml');
$category = $xml->xpath("//category[@catid='1']/text");
$ids = ['TXT1', 'TXT2', 'TXT3'];
foreach($ids as $id){
  echo $category[$id]; //I'm not quite sure how to do this bit.
}
?>

感谢您的帮助!

下面是一个如何将DOM扩展与XPATH:一起使用的示例

$doc = new DOMDocument();
$doc->loadXML($xml);
$selector = new DOMXPath($doc);
$result = $selector->query("//category[@catid='1']");
if($result->length !== 1) {
    die('BAD xml');
}
$category = $result->item(0);
$ids = array('TXT1', 'TXT2', 'TXT3');
foreach($ids as $id){
    // note $category as the second argument. meaning that the query
    // is relative to the category node and not to the root node
    $textResult = $selector->query("text[@id='$id']", $category);
    if($textResult->length < 1) {
        die('BAD xml');
    }
    $text = $textResult->item(0)->nodeValue;
    echo $text, PHP_EOL;
}

您可以使用DOMDocument::getElementById,有关更多信息,请参阅getElementById。