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を使用します:

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

w3.orgで言語の詳細

于 2012-11-20T11:33:08.673 に答える
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の配列を返すため、インデックスを使用して最初の要素を取得し、次にそのプロパティを取得できます。SimpleXmlElement0

注-要素が見つからないか見つからない場合、要素は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 に答える