gpt4 book ai didi

php - DOM getElementbyId 无法正常工作

转载 作者:可可西里 更新时间:2023-11-01 12:33:45 25 4
gpt4 key购买 nike

我在从 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() 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 with DOMDocument::validate or DOMDocument::$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

关于php - DOM getElementbyId 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11938008/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com