Php DOMDocument-设置getElementById的有效id

Php DOMDocument-设置getElementById的有效id,php,dom,Php,Dom,我正在尝试通过id获取元素,但未成功。为什么下面的代码无法找到具有给定id的元素 我已经设置了一个测试用例: <?php $m_oDom = new DOMDocument( '1.0', 'UTF-8' ); $m_oDom->formatOutput = true; $m_oDom->preserveWhiteSpace = false; $m_oDom->validateOnParse = true; $strId = "abc"; $oElement = $

我正在尝试通过id获取元素,但未成功。为什么下面的代码无法找到具有给定id的元素

我已经设置了一个测试用例:

<?php

$m_oDom = new DOMDocument( '1.0', 'UTF-8' );
$m_oDom->formatOutput = true;
$m_oDom->preserveWhiteSpace = false;
$m_oDom->validateOnParse = true;

$strId = "abc";

$oElement = $m_oDom->createElement( 'div' );    

$oAttribute = $oElement->setAttribute( 'id', $strId );

$oElement->setIdAttribute( 'id', false ); // tried also without this

$oElement->appendChild( $oAttribute );

// $oAttribute = $oElement->getAttributeNode( 'id' );

$b = $oAttribute->isId();

if( $b ) {
   echo "true";   
} else {
   echo "false"; // says false
}

$oElement = $m_oDom->getElementById( $strId );

if( $oElement ) {
   echo "element";   
} else {
   echo "false"; // says false
}

?>

我认为您正在尝试这样的方法:

$oElement = $m_oDom->createElement( 'div' );    

$oAttribute = $oElement->setAttribute( 'id', $strId );

$oElement->setIdAttribute( 'id', true ); // tried also without this

$m_oDom->appendChild( $oElement );

它向我返回true和元素输出。

“为什么下面的代码无法找到具有给定id的元素?”——因为您没有设置实际id,所以您只是创建了一个名为“id”的属性。请阅读
setIdAttribute
getElementById
上的手册!啊!!谢谢,伙计,我误读了
setIdAttribute
上的文档。将
false
更改为
true
当然做到了。。。