在PHP中使用Xpath解析XML

dan*_*car 1 php xml xpath parsing

请考虑以下代码:

$dom = new DOMDocument();
$dom->loadXML($file);

$xmlPath = new DOMXPath($dom);
$arrNodes = $xmlPath->query('*/item');
foreach($arrNodes as $item){
//missing code
}
Run Code Online (Sandbox Code Playgroud)

$ file是一个xml,每个项目都有一个标题和一个描述.如何显示它们(标题和说明)?

$file = "<item>
   <title>test_title</title>
   <desc>test</desc>
</item>";
Run Code Online (Sandbox Code Playgroud)

aul*_*ron 6

我建议使用php simplexml,使用它,你仍然可以获得xpath功能,但是使用更简单的方法,例如你可以访问这样的属性:

$name = $item['name'];
Run Code Online (Sandbox Code Playgroud)

这是一个例子:

xmlfile.xml:

<?xml version="1.0" encoding="UTF-8"?>
<xml>
    <items>
        <item title="Hello World" description="Hellowing the world.." />
        <item title="Hello People" description="greeting people.." />
    </items>
</xml>
Run Code Online (Sandbox Code Playgroud)

do.php:

<?php
$xml_str = file_get_contents('xmlfile.xml');
$xml = new SimpleXMLElement($xml_str);
$items = $xml->xpath('*/item');

foreach($items as $item) {
    echo $item['title'], ': ', $item['description'], "\n";
}
Run Code Online (Sandbox Code Playgroud)