私にとってはうまくいきます、例えば
<?php
$doc = new DOMDocument;
$doc->loadhtml(data());
foreach( $doc->getElementsByTagName('h2') as $h2 ) {
foreach( $h2->getElementsByTagName('a') as $a ) {
echo $a->getAttribute('href'), ': ', $a->nodeValue, "\n";
}
}
function data() {
return <<< eoh
<html>
<head><title>...</title></head>
<body>
<h2><a href="link1">header 1</a></h2>
<p>yadda yadda</p>
<h2><a href="link2">header 2</a></h2>
<p>yadda yadda</p>
<h2><a href="link3">header 3</a></h2>
<p>yadda yadda</p>
</body>
</html>
eoh;
}
しかし、これにはXPathを使用する方が簡単だと思います
。
<?php
$doc = new DOMDocument;
$doc->loadhtml(data());
$xpath = new DOMXPath($doc);
foreach( $xpath->query('/html/body//h2/a') as $a) {
echo $a->getAttribute('href'), ": ", $a->nodeValue, "\n";
}
function data() {
return <<< eoh
<html>
<head><title>...</title></head>
<body>
<h2><a href="link1">header 1</a></h2>
<p>yadda yadda</p>
<h2><a href="link2">header 2</a></h2>
<p>yadda yadda</p>
<h2><a href="link3">header 3</a></h2>
<p>yadda yadda</p>
</body>
</html>
eoh;
}
プリント
link1: header 1
link2: header 2
link3: header 3