2

When running this php script :

$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. Here is my counter.html file :

  <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>";

Tarik Mokafih
  • 1,247
  • 7
  • 19
  • 38

2 Answers2

2

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

Since you don't define a DTD, you could add $doc->validateOnParse = true; before you load the HTML file. This should validate against the HTML DTD and set appropriate ID attribute.

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);
cmbuckley
  • 40,217
  • 9
  • 77
  • 91
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

@ $ 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);