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

나는 윈도우 7에 XAMPP 1.7.3을 사용하고 있습니다. 제 서버에서 테스트 해본 결과 오류가없는 것으로 나타났습니다. 도움이 될 것입니다. DOMDocument::getElementById() docs에서

+0

오류 확인 : http://codepad.org/ RAknUJ5a –

+0

나는 똑같은 코드 패드를 가지고 있지만 내 서버에서는 올바르게 작동한다. Codepad는 <5.3, IIRC .... @Death, 어떤 PHP 버전을 사용하고 있습니까? –

+0

@Chris php 5.3.1 --- – undone

답변

4

, 당신은 문서 당

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

...code continues ... 

을 예상대로 수행 할 수 getElementById에 대한 문서 타입을 선언해야하는 DTD를 지정해야합니다 getElementById은 요소의 어떤 속성이 고유 식별자로 사용되는지 이해합니다. doctype을 선언하면이를 수행합니다. 당신은 명시 적으로

문서, setIdAttribute를 사용하여 (DTD를 부여하지 않고)이 설정할 수 있습니다

+0

내 코드가 서버에서 작동하는 이유를 설명 할 수 있습니까? – undone

+0

아니요, 내 서버 (PHP 5.4 포함)에서 doctype이 필요하지 않은 이유를 설명 할 수 없습니다. 나는 ** 내가 doctype을 선언해야한다는 것이 이상하다고 생각하기 때문에 알아 내려고 노력해 왔습니다. 'loadHTML'이 호출 될 때 내 서버의 PHP 인스턴스가 DTD를 가져 오는 위치는 어디입니까? 추측 하시겠습니까? –

+0

내 서버가 php 5.2이고 다른 PHP 5.3으로 테스트되었고 모두 작동합니다! – undone

6

: 당신의 HTML 만 조각이기 때문에 당신이 ID가 자신을 속성을 지시 왼쪽되도록

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.


, 그것은, DTD를 지정하지 않습니다. 같은 기본 예제는 같을 것이다

doc page에 대한 의견에서 언급 한 바와 같이
$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 
관련 문제