2012-08-13 49 views
8

我从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上。 我在我的服务器上测试过它,并且显示我没有错误。 任何帮助,将不胜感激。

+0

错误证实:http://codepad.org/ RAknUJ5a – 2012-08-13 16:18:43

+0

我在键盘上得到了同样的东西,但在我的服务器上它工作正常。键盘是<5.3,IIRC .... @Death,你正在使用什么PHP版本? – 2012-08-13 16:20:49

+0

@Chris php 5.3.1 --- – undone 2012-08-13 16:22:30

回答

4

正如关于doc page评论中指出,必须声明DOCTYPE为getElementById按预期执行

t =<<<D 
<!DOCTYPE html> 
<form id="frm-send" method="post" action="index.php" > 

...code continues ... 

%的文档中,DTD必须指定getElementById以了解元素的哪个属性被用作唯一标识符。声明一个文档类型可以完成此操作。您也可以明确设置这个(没有给出DTD)通过使用setIdAttribute

文档

+0

你能解释为什么我的代码在服务器上工作吗? – undone 2012-08-13 18:23:32

+0

不,我无法解释为什么在我的服务器上(使用PHP 5.4),doctype不是必需的。我一直在试图找出答案,因为我觉得我**不必**必须申报文档类型。在调用loadHTML时,我的服务器的PHP实例在哪里获取DTD?猜测? – 2012-08-13 18:54:26

+0

我的服务器是php 5.2,我用另一个php 5.3测试过,所有的作品!!! – undone 2012-08-14 06:16:27

6

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