使用PHP通过ID获取XML元素

时间:2013-02-05 20:13:23

标签: php xml

我在让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.
}
?>

感谢任何帮助,谢谢!

2 个答案:

答案 0 :(得分:2)

以下是一个示例,说明如何使用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;
}

答案 1 :(得分:1)

您可以使用DOMDocument :: getElementById,有关详情,请参阅getElementById