设置DOMelement的nodeValue:error:尝试获取非对象的属性 [英] Setting nodeValue of a DOMelement : error :Trying to get property of non-object
问题描述
运行此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"] ;}
我得到:试图获取非对象的属性
在最后一行
如果不是正确的方法,我该如何设置标签的文本,我必须提取它的id。
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.
这里是我的some_url.html:
here is my 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>
谢谢
推荐答案
根据官方文档, getElementById()
返回单个 DOMElement
,它扩展了 DOMNode
,它们又有你要改变的 $ nodeValue
字段。一个 DOMNode
不是一个 DOMNodeList
,所以它没有 $ length
字段和 item()
方法。因此,您不应该在该元素上调用 item()
,您可以直接操作$ code $ $ nodeValue 。要查明是否存在这样的元素,只需测试 getElementById()
的结果,以便与 NULL
(或使用 if($ element)
作为简写)。完整的代码将如下所示:
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. A DOMNode
is not a DOMNodeList
, so it has neither the $length
field nor the item()
method. Because of that, you aren't supposed to call item()
on that element, you can directly manipulate its $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). 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"];
资料来源:
http://pl1.php.net/manual/en/domdocument.getelementbyid.php
< a href =http://pl1.php.net/manual/en/class.domelement.php =nofollow> http://pl1.php.net/manual/en/class.domelement.php
http://pl1.php.net /manual/en/class.domnode.php
这篇关于设置DOMelement的nodeValue:error:尝试获取非对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!