我在从HTML表单中提取输入值时遇到了一点问题。据我所知,我的代码没有任何问题,但我找不到问题所在。
<?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
我在Windows 7上使用XAMPP 1.7.3。我在服务器上对其进行了测试,它没有显示任何错误。任何帮助将不胜感激。
来自DOMDocument::getElementById()
文档:
要使此函数正常工作,您需要使用
DOMElement::setIdAttribute
或 DTD 设置一些 ID 属性,该 DTD 将属性定义为 ID 类型。在后一种情况下,您需要在使用此功能之前使用DOMDocument::validate
或DOMDocument::$validateOnParse
验证文档。
由于您的 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
如文档页面上的评论中所述,您必须声明一个文档类型,getElementById
才能按预期执行
t =<<<D
<!DOCTYPE html>
<form id="frm-send" method="post" action="index.php" >
...code continues ...
根据文档,必须指定 DTD,以便getElementById
了解元素的哪个属性用作唯一标识符。声明文档类型可以实现此目的。您也可以通过使用 setIdAttribute
、
文档
- http://www.php.net/manual/en/domdocument.getelementbyid.php
- http://www.php.net/manual/en/domelement.setidattribute.php