getEleme-6ren">
gpt4 book ai didi

php - getElementbyId 在服务器上返回 null 但在我的本地 wamp 上工作正常

转载 作者:行者123 更新时间:2023-11-27 23:54:33 25 4
gpt4 key购买 nike

运行此 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 在我的网络服务器上被发现为空,因此它不会进入 if 条件,但它在我的本地服务器上运行良好。这是我的 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>

我已经通过以下操作确保 html 文件已成功加载:echo "<pre>".$doc->saveHTML()."</pre>";

最佳答案

来自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. In the later[sic] case, you will need to validate your document with DOMDocument::validate or DOMDocument::$validateOnParse before using this function.

因为您没有定义 DTD,所以您可以在加载 HTML 文件之前添加 $doc->validateOnParse = true;。这应该根据 HTML DTD 进行验证并设置适当的 ID 属性。

如果这对您不起作用,user-contributed notes 中提到了一个后备解决方案:

$xpath = new DOMXPath($doc);
$ele2 = $xpath->query("//*[@id='coupon_id']")->item(0);

关于php - getElementbyId 在服务器上返回 null 但在我的本地 wamp 上工作正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24824464/

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