问题描述
||
现在我在这个头上挠挠了太久了...
$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 />\";
}
我最终从中得到了我的代码:php dom获取节点的所有属性。我还尝试了其他方法,例如为单个属性调用getAttribute(),以查看是否可行,但结果相同。
我尝试通过的HTML很简单:
<a id=\"testid\" title=\"testtitle\" name=\"this is a testname\" href=\"http://example.com/\">link!</a>
我收到以下错误:
Warning: DOMDocument::loadHTML() [domdocument.loadhtml]: error parsing attribute name in Entity,line: 1
我的脚本输出:
id: testid
title: testtitle
name: this
is:
a:
testname:
href: http://example.com/
我应该补充一点,如果\'name \'属性是一个单词,则输出效果很好。
所以很明显,它必须在空间上使用explode()或一些愚蠢的东西。有没有一种方法可以解决此问题,而无需将所有空格都转换为%20之类的东西(除链接之外,我还有很多其他内容,并且不想转换整个内容块)?
解决方法
如注释中所述,“ 4”属性与“ 5”属性共享相同的空间,“ 5”属性定义为“名称令牌”,仅限字母,数字,破折号,下划线,句点和冒号。
您会注意到该列表中不允许有空格。
PHP使用的DOMDocument解析器的某些版本对HTML遵从性非常严格,遇到规范违例时会发牢骚并经常做错事。这可能是其中一种情况。从名称属性中删除空格,然后查看是否继续遇到问题。