Php 使用XPath从HTML标记获取“lang”属性
我试图在使用cURL获取的HTML标记中获取'lang'属性的值,这一切都进行得很顺利。超级清理HTML,如下所示:Php 使用XPath从HTML标记获取“lang”属性,php,html,curl,xpath,attributes,Php,Html,Curl,Xpath,Attributes,我试图在使用cURL获取的HTML标记中获取'lang'属性的值,这一切都进行得很顺利。超级清理HTML,如下所示: <html lang="en"> <head> <title>Example</title> </head> <body></body> </html> 如何在HTML元素中获取该属性的值?它出现在cURL的$response中,cURL获取我
<html lang="en">
<head>
<title>Example</title>
</head>
<body></body>
</html>
如何在HTML元素中获取该属性的值?它出现在cURL的$response中,cURL获取我执行XPath查询的页面。注意:$tag->getAttribute'lang'不会返回所需的结果,因为$tag->attributes显示为空
这对我有用 输出: 嗯
$html->item0->attributes->item0->nodeValue使它像这样“工作”已经向我表明问题出在别处。我在$response上做loadHTML,包括CURLOPT_HEADER,true,现在改做loadHTML$body,它不包含任何头。问题:解决了!
// 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
)
<?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 Object
(
[length] => 1
)