1

PHP の DomDocument クラスを使用して HTML を解析しています。

アンカーを持つhtmlを指定し、すべてのアンカーを見つけて配列に格納するように依頼すると、アンカーがないかのように空の配列が返されます。

なぜこれを行うのですか?どうすれば修正できますか?

コードは次のとおりです。

$dom = new DOMDocument();
$domObject->loadHTML($content);
$anchors = $domObject->getElementsByTagName('a');
print_r($anchors); // returns empty array.

$content は次のようになります。

     <p>
        Friend David, I do not think we shall need a call bell as Hello! can be heard 10 to 20 feet away. What you think? Edison - P.S. first cost of sender & receiver to manufacture is only $7.00.[12] Hello, hello! New York, hello!
       </p>
       <a href="http://the-irf.com/hello/hello5.html">Prev</a>
       <a href="hello7.html">Next</a>
       <a href="end.html">End</a>
    </body>
</html>
4

2 に答える 2

2

存在はどこ$domObjectに設定されていますか?これを試して:

$matchList = array();
$dom = new DOMDocument();
$dom->loadHTML($content);
$anchors = $dom->getElementsByTagName('a');
foreach($anchors as $anchor) {
    array_push($matchList, $anchor->getAttribute('href'));
}
var_dump($matchList);
于 2013-04-10T23:49:14.233 に答える
1

$dom/タイプミスを修正した後、コード$domNodeは空の配列を返さないことに注意してください。代わりに次を返します。

DOMNodeList Object
(
)

プライベート プロパティのみを持つオブジェクトが返されたことを意味します。したがって、出力では空に見えprint_r()ます。

ただし、結果は空ではなくDOMNodeList、インターフェイスを実装していIteratorます。したがって、結果を反復処理できます。

foreach($anchors as $anchor) {
    var_dump($anchor->nodeValue);
}

結果が空でないかどうかを確認する簡単な方法は、ノード リストの長さを確認することです。

echo "The query returned " . $anchors->length . " nodes";

完全な例を次に示します。

$html = <<<EOF
<html>
  <head></head>
  <body>
     <p> 
        Friend David, I do not think we shall need a call bell as Hello! can be heard 10 to 20 feet away. What you think? Edison - P.S. first cost of sender & receiver to manufacture is only $7.00.[12] Hello, hello! New York, hello!
       </p>
       <a href="http://the-irf.com/hello/hello5.html">Prev</a>
       <a href="hello7.html">Next</a>
       <a href="end.html">End</a>
    </body>
</html>
EOF;

$domObject = new DOMDocument();
$domObject->loadHTML($html);
$anchors = $domObject->getElementsByTagName('a');

$links = array();
foreach($anchors as $anchor) {
    $links[] = $anchor->getAttribute('href');
}

var_dump($links);

出力

string(36) "http://the-irf.com/hello/hello5.html"
string(11) "hello7.html"
string(8) "end.html"
于 2013-04-10T23:55:03.433 に答える