在 PHP 中使用 Xpath 解析 XML [英] Parsing an XML with Xpath in PHP
本文介绍了在 PHP 中使用 Xpath 解析 XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑以下代码:
$dom = new DOMDocument();
$dom->loadXML($file);
$xmlPath = new DOMXPath($dom);
$arrNodes = $xmlPath->query('*/item');
foreach($arrNodes as $item){
//missing code
}
$file 是一个 xml,每个项目都有一个标题和一个描述.如何显示它们(标题和描述)?
The $file is an xml and each item has a title and a description. How can I display them (title and description)?
$file = "<item>
<title>test_title</title>
<desc>test</desc>
</item>";
推荐答案
如果您的项目如下所示:
If your item looks like this:
<item>
<title>foo</title>
<description>frob</description>
</item>
您可以使用 getElementsByTagName()
和 nodeValue
:
You could use getElementsByTagName()
and nodeValue
:
foreach($arrNodes as $item){
print $item->getElementsByTagName('title')->item(0)->nodeValue;
}
title
和 description
是属性吗?例如一个项目看起来像这样:
Are title
and description
attributes? E. g. does an item look like this:
<item title="foo" description="frob" />
如果是这样,你可以使用 getAttribute()
:
If so, you could just use getAttribute()
:
...
foreach($arrNodes as $item){
print $item->getAttribute('title');
}
这篇关于在 PHP 中使用 Xpath 解析 XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文