【问题标题】:PHP Dom problem, how to insert html code in a particular divPHP Dom问题,如何在特定的div中插入html代码
【发布时间】:2011-02-28 03:19:18
【问题描述】:

我正在尝试将 div 'resultsContainer' 中的 html 代码替换为 $response 的 html。

我的代码不成功的结果是“resultsContainer”的内容仍然存在,并且 $response 的 html 在屏幕上显示为文本而不是被解析为 html。

最后,我想在 'resultContainer' 中注入 $response 的内容,而不必创建任何新的 div,我需要这个:<div id='resultsContainer'>Html inside $response here...</div> 而不是这个:<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', $response);
      $doc->getElementById('resultsContainer')->appendChild($node);


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

【问题讨论】:

    标签: php dom parsing replace


    【解决方案1】:

    如果 $reponse 是纯文本:

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

    如果它(可以)包含 html(可以使用 createDocumentFragment,但这会在实体、dtd 等方面产生自己的一系列问题):

    // 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));
    }
    

    这表明将 DOMDocuments 用作模板引擎确实不太适合(或至少很麻烦)。

    【讨论】:

    • 嘿,问题是 $response 不是纯文本而是 html,我真正需要的是替换 'resultsContainer' 的内容而不是附加到它
    • 所以取第二个选项,如果需要清空元素,在foreach循环之前通过$frag进行: foreach($target->childNodes as $node) $target->removeChild( $节点);
    • 非常感谢,我会尝试并告诉你进展如何
    • 当我这样做时,我得到:警告:为 foreach() 提供的参数无效 // 空目标容器 $target = $doc->getElementById('resultsContainer'); foreach($target->childNodes as $node){ $target->removeChild($node); }
    • 可能是因为 $target 的类型是 DOMElement 而不是 DOMNode?​​span>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-02
    • 2018-06-04
    • 2014-03-30
    • 2011-05-03
    • 2018-10-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多