检查domnodelist-> item(x) - > nodeValue =="nbsp;"

tom*_*tom 2 php xpath dom domdocument domxpath

我已经登录,并使用CURL,抓住返回页面,加载它,DOMDocument然后查询它DOMXPATH(找到'table.essgrid tr').(我当时也查询结果以找到孩子的'td'和)结果,results->item(2)->nodeValue是日期或浏览器中的回声为 . I need to check if it will be a non break space or actual text.

Hopefully that makes some sense with the code below.

$dom = new DOMDocument();
$dom->loadHTML($result);

$xpath = new DOMXPATH($dom);
$result = $xpath->query('//table[@class="essgrid"]//tr');
if($result->length > 0) {
    foreach($result as $item) {
        $tds = $item->getElementsByTagName('td');

        if($tds->length) {
            if($tds->item(2)->nodeValue != " " && $tds->item(2)->nodeValue != " ") {
                echo = '<div>not blank:</div>';
                echo = '<div>'.$tds->item(2)->nodeValue.'</div>';
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

So I am wanting this to only echo the "table.essgrid>tr>td" that have a value that isnt a non-breaking space, but it just echos this onto the page:

<div>not blank:</div>
<div>&nbsp;</div>
<div>not blank:</div>
<div>&nbsp;</div>
<div>not blank:</div>
<div>13:00</div>
<div>not blank:</div>
<div>&nbsp;</div>
<div>not blank:</div>
<div>14:30</div>
<div>not blank:</div>
<div>13:00</div>
<div>not blank:</div>
<div>&nbsp;</div>
Run Code Online (Sandbox Code Playgroud)

But it is echoing all the results, not just the ones with a time. So I think my problem is checking if the value == &nbsp;,但我在其位置上尝试的任何内容似乎都无效.

hak*_*kre 5

当你想比较nodeValue的幸福&nbsp;,你需要知道两件事情:

  1. &nbsp;是一个表示特定字符​​的HTML实体,这里是非破坏性空间,可以正式指定为Unicode字符"NO-BREAK SPACE"(U + 00A0).
  2. 在给出或接受字符串值时,DOMDocument库使用UTF-8作为字符编码.

有了这些一般信息,您就可以轻松解决问题.作为&nbsp;代表NO-BREAK SPACE(U + 00A0)DOMElement::nodeValue回报的内容作为UTF-8编码字符串和NO-BREAK SPACE在UTF-8是"\xC2\xA0"在PHP中,你可以简单地比较一下:

/** @var $td DOMElement */
$td = $tds->item(2);
if ($td->nodeValue !== "\xC2\xA0") {
    // TD content is not "&nbsp;"
}
Run Code Online (Sandbox Code Playgroud)

希望这能为您提供所需的指针.