dongyan5141 2013-07-18 12:20
浏览 46
已采纳

DOMDOCUMENT | PHP:将getElementById输出保存到新的HTML文件中

I'm trying to save the result of getElementById using PHP.

The code I have:

<?php
$doc = new DOMDocument();
$doc->validateOnParse = true;
@$doc->loadHTMLfile('test.htm');
$div = $doc->getElementById('storytext');
echo $doc->saveHTML($div);
?>

This displays the relevant text, I now want to save that to a new file, I have tried using save(), saveHTMLfile() and file_put_contents(), none of those work because they only save strings and I cannot turn $div into a string, so I'm stuck.

If I just save the entire thing:

$doc->saveHTMLfile('name.ext');

It works but it saves everything, not just the part that I need.

I'm a complete DOM noob so I may be missing something very simple but I can't really find much about this through my searches.

  • 写回答

1条回答 默认 最新

  • doudang8824 2013-07-18 12:23
    关注
    function getInnerHtml( $node ) { 
        $innerHTML= ''; 
        $children = $node->childNodes; 
        foreach ($children as $child) { 
            $innerHTML .= $child->ownerDocument->saveXML( $child ); 
        } 
    
        return $innerHTML; 
    }
    
    $html = getInnerHtml($div);
    file_put_contents("name.ext", $html);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?