0

xml 数据如下所示:

<feed>    
    <entry>
      <id>12345</id>
      <title>Lorem ipsum</title>
      <link type="type1" href="https://foo.bar" />
      <link type="type2" href="https://foo2.bar"/>
    </entry>
    <entry>
      <id>56789</id>
      <title>ipsum</title>
      <link type="type2" href="https://foo4.bar"/>
      <link type="type1" href="https://foo3.bar" />
    </entry>
</feed>

我想从特定类型的链接中选择 href 属性的内容。(请注意,类型 1 并不总是第一个链接)

部分有效的代码:

for($i=0; $i<=5; $i++) {
    foreach($xml->entry[$i]->link as $a) {
        if($a["type"] == "type2")
            $link = (string)($a["href"]);
    }
}

但是,我想知道是否有不需要 foreach 循环的更快、更优雅的解决方案。有任何想法吗?

4

2 回答 2

0

您是否尝试过使用 xpath?http://php.net/manual/en/simplexmlelement.xpath.php

这将允许您搜索具有指定标签/属性的节点。

$nodes = $xml->xpath('//link[@type="type2"]');
foreach ($node in $nodes)
{
    $link = $node['href'];
}

// 更新

如果您只对第一个值感兴趣,则可以跳过 for 循环。该xpath函数返回一个对象数组,SimpleXmlElement因此您可以使用索引0来检索第一个元素,然后是它的属性。

注意 - 如果元素丢失或找不到,xpath元素将返回false,并且下面的代码将出错。该代码仅用于说明,因此您应该在实现它时验证错误检查。

// This will work if the xml always has the required attrbiute - will error if it's missing
$link = $xml->xpath('//link['@type="type2"]')[0]['href'];
于 2012-11-20T11:34:57.743 回答
0

使用xpath

$xml->xpath('//link[@type="type2"]');

更多关于w3.org的语言

于 2012-11-20T11:33:08.673 回答