【问题标题】:PHP Xpath extracting a value for a node with attribute name="author"PHP Xpath 为具有属性 name="author" 的节点提取值
【发布时间】:2011-05-16 00:52:33
【问题描述】:

我正在尝试解析一些 XML 数据以获取某个属性的值 - 具体来说,我想找到作者。下面是一个非常精简但有效的示例。 R 节点重复多次。

<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 次,但可能根本不存在(我可以自己处理)

【问题讨论】:

    标签: php xml parsing xpath


    【解决方案1】:

    这里是解决方案。基本上,您可以对结果节点进行 XPath 调用,以获取 name 属性等于 author 的所有属性元素。

    然后您检查并确保返回了一个结果,如果返回,它将是 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
        }
    }
    

    【讨论】:

    • 谢谢,这行得通 - 你能解释一下为什么你不需要指定节点的路径吗?您是否只是在寻找具有name="author" 属性的任何节点?如果是这样,那很好,但我只是好奇。干杯
    • @Basiclife 是的,它正在从当前&lt;R&gt; 元素的上下文中寻找任何具有name="author" 属性的属性节点。
    【解决方案2】:
    $authors = $Result->xpath('PageMap/DataObject/Attribute[@name="author"]');
    if (count($authors)) {
        $author = (string) $authors[0]['value'];
    }
    

    【讨论】:

    • 谢谢,选择了节点。也许我不清楚,但是如何为该节点选择“值”的内容?抱歉,我对 XPath 很陌生
    • @Basiclife $author 设置为数组中第一个元素的value 属性
    猜你喜欢
    • 1970-01-01
    • 2011-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多