使用xpath通配符获取“图标”和“快捷方式图标”
问题描述:
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?
我正在尝试使用xpath通配符来获取favicon: p> \ n
$ doc = new DOMDocument();
$ doc-> strictErrorChecking = FALSE;
$ doc-> loadHTML(file_get_contents($ url));
$ xml = simplexml_import_dom($ doc);
code> pre>
在这里,我正在测试“快捷图标”和“图标”(使用三元运算符): p>
$ query = $ xml-> xpath('// link [@ rel =“快捷图标”]');
$ arr =(空($查询)?$ xml-&gt ; xpath('// link [@ rel =“icon”]'):$ query);
$ favicon = $ arr [0] ['href'];
code> pre>
它有效,但不是很优雅; 是否有通配符( * code>)方法同时获取“快捷图标”和“图标”? p>
div>
答
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"]