[英]Setting nodeValue of a DOMelement : error :Trying to get property of non-object
When running this php script : 运行此php脚本时:
$doc = new DOMDocument();
$doc->loadHTMLFile("some_url.html");
$ele1 = $doc->getElementById ( "coupon" );
if($ele1->length){
$doc->getElementById ( "coupon" )->item(0)->nodeValue =$result["affiliate_name"] ;}
I get : Trying to get property of non-object
in the last line if it's not the right way to do it, how can I set the text of tag that I must extract usig its Id. 我得到:如果这不是正确的方法,则Trying to get property of non-object
在最后一行Trying to get property of non-object
,如何设置必须提取usig其ID的标记的文本。
here is my some_url.html : 这是我的some_url.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>
Thank you 谢谢
According to the official documentation, getElementById()
returns a single DOMElement
, which extends DOMNode
, which in turn has the $nodeValue
field you are trying to change. 根据官方文档, getElementById()
返回单个DOMElement
,该DOMElement
扩展了DOMNode
,而后者又具有您要更改的$nodeValue
字段。 A DOMNode
is not a DOMNodeList
, so it has neither the $length
field nor the item()
method. DOMNode
不是DOMNodeList
,因此它既没有$length
字段,也没有item()
方法。 Because of that, you aren't supposed to call item()
on that element, you can directly manipulate its $nodeValue
. 因此,您不应该在该元素上调用item()
,而是可以直接操纵其$nodeValue
。 To find out whether such element exists, simply test the result of getElementById()
for equality with NULL
(or use if ($element)
as a shorthand). 要找出此类元素是否存在,只需测试getElementById()
的结果是否等于NULL
(或使用if ($element)
作为简写)。 Complete code would look as follows: 完整的代码如下所示:
$doc = new DOMDocument();
$doc->loadHTMLFile("some_url.html");
$ele1 = $doc->getElementById("coupon");
if ($ele1) $ele1->nodeValue = $result["affiliate_name"];
Sources: 资料来源:
http://pl1.php.net/manual/en/domdocument.getelementbyid.php http://pl1.php.net/manual/en/domdocument.getelementbyid.php
http://pl1.php.net/manual/en/class.domelement.php http://pl1.php.net/manual/en/class.domelement.php
http://pl1.php.net/manual/en/class.domnode.php http://pl1.php.net/manual/en/class.domnode.php
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.