【问题标题】:Get 'lang' attribute from HTML tag using XPath使用 XPath 从 HTML 标记中获取“lang”属性
【发布时间】:2015-07-31 21:42:01
【问题描述】:

我正在尝试在 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 元素中获取此属性的值?它存在于获取页面(我在其上执行 XPath 查询)的 cURL 的 $response 中。注意:$tag->getAttribute('lang') 不会返回想要的结果,因为 $tag->attributes 看起来是空的。

【问题讨论】:

  • $html-&gt;item(0)-&gt;attributes-&gt;item(0)-&gt;nodeValue

标签: php html curl xpath attributes


【解决方案1】:

这对我有用。

<?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
)
zh

【讨论】:

  • 让它像这样“工作”向我表明问题出在其他地方。我在 $response 上执行 loadHTML(包括 CURLOPT_HEADER,true),现在已切换到不包含任何标题的 loadHTML($body)。问题:解决了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多