PHP Xpath为属性名称为"author"的节点提取值. [英] PHP Xpath extracting a value for a node with attribute name="author"
问题描述
我正在尝试解析一些XML数据以获得某个属性的值-具体来说,我想找到作者.以下是一个非常简短但有效的示例. R
节点重复多次.
I'm trying to parse some XML data to get the value of a certain attribute - Specifically, I want to find the author. Below is a very cut-down but valid example. The R
node is repeated multiple times.
<GSP VER="3.2">
<RES SN="1" EN="10">
<R N="4" MIME="application/pdf">
<Label>_cse_rvfaxixpaw0</Label>
<PageMap>
<DataObject type="metatags">
<Attribute name="creationdate" value="D:20021024104222Z"/>
<Attribute name="author" value="Diana Van Winkle"/>
</DataObject>
</PageMap>
</R>
</RES>
</GSP>
我目前正在这样做:
$XML = simplexml_load_string($XMLResult);
$XMLResults = $XML->xpath('/GSP/RES/R');
foreach($XMLResults as $Result) {
$Label = $Result->Label;
$Author = ""; // <-- How do I get this?
}
有人可以向我解释如何提取作者"属性吗? author属性最多可以出现1次,但可能根本不存在(我自己可以解决)
Can someone please explain to me how I can pull out the "author" attribute? The author attribute will be present a maximum of 1 times but may not be present at all (I can handle that myself)
推荐答案
以下是解决方案.基本上,您可以使XPath退出结果节点,以获取名称属性等于author的所有属性元素.
Here is the solution. Basically you can make an XPath call off the result node to get all attribute elements with the name attribute equal to author.
然后您检查并确保结果返回,如果返回,则它将为index [0],因为XPath调用返回结果数组.然后,使用attributes()
函数获取属性的关联数组,最后获取所需的值.
Then you check and make sure a result came back, and if it did, it will be index[0] since XPath calls return an array of results. Then you use the attributes()
function to get an associate array of the attribute, finally getting the value you want.
$XML = simplexml_load_string($xml_string);
$XMLResults = $XML->xpath('/GSP/RES/R');
foreach($XMLResults as $Result) {
$Label = $Result->Label;
$AuthorAttribute = $Result->xpath('//Attribute[@name="author"]');
// Make sure there's an author attribute
if($AuthorAttribute) {
// because we have a list of elements even if there's one result
$attributes = $AuthorAttribute[0]->attributes();
$Author = $attributes['value'];
}
else {
// No Author
}
}
这篇关于PHP Xpath为属性名称为"author"的节点提取值.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!