开发者

PHP Dom problem, how to insert html code in a particular div

I am trying to replace the html code inside the div 'resultsContainer' with the html of $response.

The result of my unsuccessful code is that the contents of 'resultsContainer' remain and the html of $response shows up on screen as text rather than being parsed as html.

Finally, I would like to inject the content of $response inside 'resultContainer' without having to create any new div, I need this: <div id='resultsContainer'>Html inside $response here...</div> and NOT THIS: <div id='resultsContainer'><div>Html inside $response here...</div></div>

   // Set Config
      libxml_use_internal_errors(true);   

      $doc = new DomDocument();
      $doc->strictErrorChecking = false;  
      $doc->validateOnParse = true;

      // load the html page
      $app = file_get_contents('index.php');

      $doc->loadHTML($app);

      // get the dynamic content
      $response = file_get_contents('search.php'.$query);
      $response = utf8_decode($response);         

      // add dynamic content to corresponding div
      $node = $doc->createElement('div', $res开发者_如何学JAVAponse);
      $doc->getElementById('resultsContainer')->appendChild($node);


      // echo html snapshot
      echo $doc->saveHTML();


if $reponse is plain text:

// add dynamic content to corresponding div
$node = $doc->createTextNode($response);
$doc->getElementById('resultsContainer')->appendChild($node);

if it (can) contain html (one could use createDocumentFragment but that creates its own set of trouble with entities, dtd, etc.):

// add dynamic content to corresponding div
$frag = new DomDocument();
$frag->strictErrorChecking = false;  
$frag->validateOnParse = true;
$frag->loadHTML($response);
$target = $doc->getElementById('resultsContainer');
if(isset($target->childNodes) && $target->childNodes->length)){
    for($i = $target->childNodes->length -1; $i >= 0;$i--){
        $target->removeChild($target->childNodes->item($i));
    }
}
//if there's lots of content in $target, you might try this:
//$target->parentNode->replaceChild($target->cloneNode(false),$target);
foreach($frag->getElementsByTagName('body')->item(0)->childNodes as $node){
   $target->appendChild($doc->importNode($node,true));
}

Which goes to show it really isn't that suited (or at least cumbersome) to use DOMDocuments as a templating engine.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜