在PHP中使用XPath解析XML

时间:2017-10-07 06:17:12

标签: php xml xpath

我只需要回显ID和标题,我已经使用Xpath和xml来获取详细信息......我需要在单独的行中回显每个ID和标题......

<?php
$xml = <<< XML
<data>
    <metadata>
        <total_elements>183</total_elements>
        <elements_per_page>100</elements_per_page>
        <total_pages>2</total_pages>
    </metadata>
    <spl>
        <id>ID1</id>
        <version>2</version>
        <title>Title 1</title>
        <published_date>Oct 06, 2017</published_date>
    </spl>
    <spl>
        <id>ID2</id>
        <version>2</version>
        <title>Title 2</title>
        <published_date>Oct 05, 2017</published_date>
    </spl>
    <spl>
        <id>ID3</id>
        <version>2</version>
        <title>Title 3</title>
        <published_date>Oct 04, 2017</published_date>
    </spl>
</data>
XML;

$errorSetting = libxml_use_internal_errors(TRUE);
$feed = new DOMDocument();
$feed->loadXML($xml);
libxml_clear_errors();
libxml_use_internal_errors($errorSetting);

$xpath = new DOMXPath($feed);

foreach ($xpath->query('//spl') as $spl) {
    foreach ($spl->childNodes as $child) 
    {
        if (($child->nodeValue) !== '') 
        {
            echo \htmlspecialchars($child->nodeValue);

        }
    }
}
?>

这给出了输出:

ID1
2
Title 1
Oct 06, 2017

ID2
2
Title 2
Oct 05, 2017

ID3
2
Title 3
Oct 04, 2017

或者我尝试过:

foreach ($xpath->query('//id') as $id) 
    {
        if (($id->nodeValue) !== '') {
         echo \htmlspecialchars($id->nodeValue);                
        }
    foreach ($xpath->query('//title') as $title) { 
        echo \htmlspecialchars($title->nodeValue); 
        }

    }

但它将输出视为:

ID1 Title 1 Title 2 Title 3
ID2 Title 1 Title 2 Title 3
ID3 Title 1 Title 2 Title 3

我需要输出为:

ID1 Title 1
ID2 Title 2
ID3 Title 3

1 个答案:

答案 0 :(得分:2)

如果您将foreach循环更改为

foreach ($xpath->query('//spl') as $spl) {
    echo $xpath->evaluate("string(descendant::id/text())", $spl);
    echo $xpath->evaluate("string(descendant::title/text())", $spl);
    echo PHP_EOL;
}

这循环遍历所有spl元素,然后是内部XPath,获取id和title(后代确保它只是封闭元素中的项)。使用evaluate()意味着在这种情况下,返回的值不是提取节点,而是字符串。同样在evaluate()我使用$spl作为查询的起点。