What are reasons why an XPath query could only return the last match? I am running a query on an HTML fragment which clearly has multiple <a name="..."> tags, but the XPath query will only return one element, which happens to be the last element.
function extract($html) {
// This test shows that the retrieved HTML fragment indeed contains multiple anchor tags
echo "<textarea>".$html."</textarea>";
// parse the data
$dom = new DomDocument();
@$dom->loadHTML($html); // we use @$dom to suppress some warnings
$xpath = new DOMXPath($dom);
// find the html code for the post
$query = "//a[contains(@name, 'post')]";
$rows = $xpath->query($query);
// This will return 1
echo "Elements found: " . count($rows);
...
}
You need to probe
$rows->length. The reason is that$rowsis an instance ofDOMNodeList(an object that holds a list ofDOMNodeinstances). And sinceDOMNodeListdoesn’t implement the interfaceCountable, it cannot be probed bycount()the way you’d expect. It simply returns1, because it is a single object, not the amount ofDOMNodes it has aggregated.And so, the result of your query does not return only the last match. It returns them all, and you can iterate through them with
foreach, like so:… or with a
forloop, like so:… etc.