0

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

XML:文本.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.
}
?>

任何帮助表示赞赏,谢谢!

4

2 回答 2

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;
}
于 2013-02-05T20:25:59.593 回答
1

您可以使用 DOMDocument::getElementById,更多信息请参见getElementById

于 2013-02-05T20:16:27.113 回答