设置DOMelement的nodeValue:getElementbyId返回null

时间:2014-07-18 11:26:27

标签: php html dom

运行这个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被发现为null,所以它没有进入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文件已成功加载

1 个答案:

答案 0 :(得分:0)

您的$doc->getElementById返回空值。你必须找出原因?

使用Xpath你可以实现这个

<?php

$xml = '<div class="panel panel-success">
    <div class="panel-heading">
      <h3 id="coupon" class="panel-title">Coupon name 1</h3>
    </div>

<p id="coupon_id">coupon id</p>

    <div id="counter-up" class="panel-body">
      0
    </div>
  </div>';


//create dom object  
$doc = new DOMDocument();

//load xml string
$doc->loadHTML($xml);

$xpath = new DOMXPath($doc);

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

$result->nodeValue = 'hello world';

echo $doc->saveHTML();

此处列出了另外两种可能对您有用的解决方案

<?php

$xml = '<div class="panel panel-success">
    <div class="panel-heading">
      <h3 id="coupon" class="panel-title">Coupon name 1</h3>
    </div>

<p id="coupon_id">coupon id</p>

    <div id="counter-up" class="panel-body">
      0
    </div>
  </div>';


//create dom object  
$doc = new DOMDocument();

//load xml string
$doc->loadHTML($xml);

//create element objects
$ele2 = $doc->getElementsByTagName("p");

//process each object element
foreach($ele2 as $obj)
{
    //change thenode value
     $obj->nodeValue = 'hello';
}

//display the html
echo $doc->saveHTML();
?>

使用简单的XML,您可以像下面这样实现

<?php 

//create object from the string
$simplxml = simplexml_load_string($xml);

//overwrite the first p tag value
$simplxml->p = 'hello world';

//display the xml
echo $simplxml->asXML();

//check you object details in debug function
print_r($simplxml);