我试图在HTML标签中获得'lang'属性的值(使用cURL获取,这一切都很顺利)。超级清理的HTML如下所示:
<html lang="en">
<head>
<title>Example</title>
</head>
<body></body>
</html>
当我使用
// Get HTML tag
$html = $xpath->query('//html');
echo '<pre>'. print_r($html, true) .'</pre>';
// Does a HTML tag exist at all?
if($html->length == 0) {
$htmlUsed = false;
}
// If HTML tag exists get value
if($html->length > 0) {
foreach($html as $tag) {
echo '<pre>'. print_r($tag->attributes, true) .'</pre>';
foreach($tag->attributes as $attribute) {
echo $attribute;
}
}
}
它打印:
DOMNodeList Object
(
[length] => 1
)
DOMNamedNodeMap Object
(
[length] => 0
)
如何在HTML元素中获得此属性的值?它出现在获取页面的cURL的$响应中(我在其上执行XPath查询)。注意:$tag->getAttribute('lang')不会返回期望的结果,因为$tag->attributes看起来是空的。
这对我来说很有用。
<?php
$doc = new DOMDocument();
$doc->loadHTML('<html lang="en">
<head>
<title>Example</title>
</head>
<body></body>
</html>');
$xpath = new DOMXPath($doc);
$html = $xpath->query('//html');
echo '<pre>'. print_r($html, true) .'</pre>';
// Does a HTML tag exist at all?
if($html->length == 0) {
$htmlUsed = false;
}
// If HTML tag exists get value
if($html->length > 0) {
foreach($html as $tag) {
echo $tag->getAttribute('lang');
}
}
输出:<>以前DOMNodeList对象([长度]=> 1)以前在