2011-05-16 109 views
3

我想解析一些XML数据以获得某个属性的值 - 具体来说,我想找到作者。下面是一个非常简单但有效的例子。 R节点重复多次。PHP的Xpath提取属性名称=“作者”节点的值

<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? 
} 

可有人请向我解释,我怎么能拉出来的“作者”属性?笔者属性将出现最大的1次,但可能不会出现在所有的(我可以处理我自己)

回答

4

这里是解决方案。基本上,您可以关闭结果节点以获取名称属性等于作者的所有属性元素。

然后您检查并确保返回结果,如果结果为真,那么它将是index [0],因为XPath调用会返回结果数组。然后,您使用attributes()函数来获取该属性的关联数组,最后获得所需的值。

$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 
    } 
} 
+0

谢谢,那有效 - 你能解释一下为什么你不需要指定节点的路径?你只是在寻找具有'name =“author”'属性的任何节点吗?如果是这样,那很好,但我只是好奇。干杯 – Basic 2011-05-16 01:12:05

+0

@Basiclife是的,它正在从当前的''元素的上下文中寻找具有'name =“author”'属性的任何Attribute节点。 – 2011-05-16 01:13:34

2
$authors = $Result->xpath('PageMap/DataObject/Attribute[@name="author"]'); 
if (count($authors)) { 
    $author = (string) $authors[0]['value']; 
} 
+0

谢谢,选择节点。也许我不清楚,但我怎样才能选择该节点的“价值”的内容?对不起,我对XPath非常陌生 – Basic 2011-05-16 01:07:46

+0

@Basiclife'$ author'被设置为数组第一个元素的'value'属性 – Phil 2011-05-16 01:13:19

相关问题