Search code examples
phphtmlxpathfavicon

Get both "icon" and "shortcut icon" using xpath wildcard


I'm trying to find out how to use xpath wildcard to get the favicon :

$doc = new DOMDocument();
$doc->strictErrorChecking = FALSE;
$doc->loadHTML(file_get_contents($url));
$xml = simplexml_import_dom($doc);

Here, i'm testing both "shortcut icon" and "icon" (using a ternary operator) :

$query = $xml->xpath('//link[@rel="shortcut icon"]');

$arr = (empty($query) ? $xml->xpath('//link[@rel="icon"]') : $query);

$favicon = $arr[0]['href'];

It works, but it's not very elegant ; Is there a wildcard (*) method to to get both "shortcut icon" and "icon" in one go?


Solution

  • You could use contains:

    //link[contains(@rel, "icon")]
    

    This would match any link element that has the text "icon" within its rel attribute.

    Note: If you know that the rel attribute will always be "icon" and "shortcut icon", it might be safer to be explicit. That way you do not get some other link that happens to include "icon".

    //link[@rel="icon" or @rel="shortcut icon"]