Question: 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>";`

Answer: 
From the [documentation](http://php.net/domdocument.getelementbyid):

> 
> For this function to work, you will need either to set some ID attributes with [DOMElement::setIdAttribute](http://php.net/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](http://php.net/domdocument.validate) or [DOMDocument::$validateOnParse](http://php.net/domdocument#domdocument.props.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](http://php.net/domdocument.getelementbyid#96500):

```
$xpath = new DOMXPath($doc);
$ele2 = $xpath->query("//*[@id='coupon_id']")->item(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);`