DOM getElementbyId无法正常工作
问题描述:
我从HTML表单中提取输入值时遇到了一些问题。据我所知,我的代码没有问题,但我找不到问题所在。DOM getElementbyId无法正常工作
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$t =<<<D
<form id="frm-send" method="post" action="index.php" >
<input type="text" name="data[postusername]" id="postusername" value="user" />
<input type="checkbox" name="data[save]" id="data[save]" value="1" />
<input type="hidden" name="secret" id="secret" value="0d35635c0cb11760789de6c4fe35e046311f724b" />
<input type="submit" name="btnSubmit" id="btnSubmit" value="Send" />
<input type="hidden" name="data[checkgetrequest]" value="true" id="data[checkgetrequest]" />
<input type="hidden" name="frm-id" value="13448477965028bfb44222d" id="frm-id" />
</form>
<input type="text" id="getfocus_txt_13448477965028bfb44222d" name="getfocus_txt_13448477965028bfb44222d" />
D;
$dom = new domDocument;
$dom->loadHTML($t);
$dom->preserveWhiteSpace = true;
$frmid = $dom->getElementById('frm-id') ;
echo $frmid->getAttribute('value');
?>
它显示了我的错误:
Fatal error: Call to a member function getAttribute() on a
non-object in E:\Apache\msg.php on line 22
我使用的XAMPP 1.7.3在Windows 7上。 我在我的服务器上测试过它,并且显示我没有错误。 任何帮助,将不胜感激。
答
正如关于doc page评论中指出,必须声明DOCTYPE为getElementById
按预期执行
t =<<<D
<!DOCTYPE html>
<form id="frm-send" method="post" action="index.php" >
...code continues ...
%的文档中,DTD必须指定getElementById
以了解元素的哪个属性被用作唯一标识符。声明一个文档类型可以完成此操作。您也可以明确设置这个(没有给出DTD)通过使用setIdAttribute
,
文档
答
从DOMDocument::getElementById()
docs:
For this function to work, you will need either to set some ID attributes with
DOMElement::setIdAttribute
or a DTD which defines an attribute to be of type ID. In the later case, you will need to validate your document withDOMDocument::validate
orDOMDocument::$validateOnParse
before using this function.
由于您的HTML只是一个片段,它没有指定一个DTD,所以你留下口述的ID属性自己。一个基本的例子看起来像:
$html = '<div><p id="a">Para A</p><p id="b">Para B</p></div>';
$dom = new DOMDocument;
$dom->loadHTML($html);
// Set the ID attribute to be "id" for each (non-ns) element that has one.
foreach ($dom->getElementsByTagName('*') as $element) {
if ($element->hasAttribute('id')) {
$element->setIdAttribute('id', true);
}
}
$p = $dom->getElementById('b');
echo $p->textContent; // Para B
错误证实:http://codepad.org/ RAknUJ5a – 2012-08-13 16:18:43
我在键盘上得到了同样的东西,但在我的服务器上它工作正常。键盘是 2012-08-13 16:20:49
@Chris php 5.3.1 --- – undone 2012-08-13 16:22:30