[英]getElementbyId returns null on server but works fine on my local wamp
When running this php script :运行此 php 脚本时:
$doc = new DOMDocument();
$doc->loadHTMLFile("../counter.html");
$ele2 = $doc->getElementById ( "coupon_id" );
if($ele2){
$ele2->nodeValue = $result["coupon_code"];
}
$response["list"]= $doc->saveHTML();
$ele2 is found to be null on my web server an so it does not enter to the if condition, but it works fine on my local server.发现 $ele2 在我的 Web 服务器上为空,因此它不会进入 if 条件,但它在我的本地服务器上运行良好。 Here is my counter.html file :
这是我的 counter.html 文件:
<div class="panel panel-success">
<div class="panel-heading">
<h3 id="coupon" class="panel-title">Coupon name 1</h3>
</div>
<p id="coupon_id" hidden>coupon id</p>
<div id="counter-up" class="panel-body">
0
</div>
</div>
I already made sure the html file was loaded successfully by doing : echo "<pre>".$doc->saveHTML()."</pre>";
我已经通过执行以下操作确保 html 文件已成功加载:
echo "<pre>".$doc->saveHTML()."</pre>";
From the documentation :从文档:
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.
要使此函数工作,您需要使用DOMElement::setIdAttribute或 DTD 设置一些 ID 属性,该 DTD 将属性定义为 ID 类型。 In the later [ sic ] case, you will need to validate your document with DOMDocument::validate or DOMDocument::$validateOnParse before using this function.
在后面的[原文如此] 的情况下,在使用此函数之前,您需要使用DOMDocument::validate或DOMDocument::$validateOnParse验证您的文档。
Since you don't define a DTD, you could add $doc->validateOnParse = true;
由于您没有定义 DTD,您可以添加
$doc->validateOnParse = true;
before you load the HTML file.在加载 HTML 文件之前。 This should validate against the HTML DTD and set appropriate ID attribute.
这应该根据 HTML DTD 进行验证并设置适当的 ID 属性。
If that doesn't work for you, there's a fallback solution mentioned in the user-contributed notes :如果这对您不起作用,则用户提供的注释中提到了一个后备解决方案:
$xpath = new DOMXPath($doc);
$ele2 = $xpath->query("//*[@id='coupon_id']")->item(0);
The addition of <!添加 <! DOCTYPE html PUBLIC "- // W3C // DTD HTML 4.0 Transitional // EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> helped me
DOCTYPE html PUBLIC "- // W3C // DTD HTML 4.0 Transitional // EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> 帮助了我
@ $ doc-> loadHTML ('<? xml encoding = "UTF-8"> <! DOCTYPE html PUBLIC "- // W3C // DTD HTML 4.0 Transitional // EN" "http://www.w3.org/ TR / REC-html40 / loose.dtd "> '. $ html);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.