2012-08-13 48 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