将 DOMNode->attributes 与值中包含多个单词的属性一起使用时出现问题

And*_*yno 4 php domdocument

我已经为这个问题挠头太久了……

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

$links = $dom->getElementsByTagName( 'a' )->item( 0 );
foreach ( $links->attributes as $attribute ) {
    $name = $attribute->nodeName;
    $value = str_replace( '"', '', stripslashes( $attribute->nodeValue ) );
    echo "$name: $value<br />";
}
Run Code Online (Sandbox Code Playgroud)

我最终得到了我的代码:php dom get all attribute of a node。我还尝试了其他方法,例如为单个属性调用 getAttribute() 以查看是否有效,但得到了相同的结果。

我试图浏览的 HTML 很简单:

<a id="testid" title="testtitle" name="this is a testname" href="http://example.com/">link!</a>
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

Warning: DOMDocument::loadHTML() [domdocument.loadhtml]: error parsing attribute name in Entity, line: 1
Run Code Online (Sandbox Code Playgroud)

我的脚本输出:

id: testid
title: testtitle
name: this
is: 
a: 
testname: 
href: http://example.com/
Run Code Online (Sandbox Code Playgroud)

我应该补充一点,如果“名称”属性是一个单词,则输出工作正常。

很明显,它一定是在空间上使用了explode()或者一些愚蠢的东西。有没有办法解决这个问题,而无需将所有空格转换为 %20 或其他内容(除了链接之外,我还有很多其他内容,并且不想转换整个内容块)?

Cha*_*les 5

正如注释中所指出的,该属性与被定义为“NAME token”的name属性共享相同的空间,该属性仅限于字母、数字、破折号、下划线、句点和冒号。id

您会注意到该列表中不允许有空格。

PHP 使用的 DOMDocument 解析器的某些版本对于 HTML 合规性非常严格,并且在遇到违反规范的情况时会抱怨并经常做错误的事情。这可能是其中之一。从您的名称属性中删除空格,然后查看问题是否仍然存在。