编程语言
首页 > 编程语言> > php打开修改并保存html文件

php打开修改并保存html文件

作者:互联网

在php中,我想打开一个html文件,删除div(class Areas)的内容并保存.

$dom = new DOMDocument;
$dom->loadHTMLFile( "temp/page".$y.".xhtml" );
$xpath = new DOMXPath( $dom );
$pDivs = $xpath->query(".//div[@class='Areas']");
foreach ( $pDivs as $div ) {
  $div->parentNode->removeChild( $div );
}
echo htmlspecialchars($dom->saveHTMLFile());

没用…

我的html文件外观:

<html>
 <head>
  <title></title>
  <link href="css.css" rel="stylesheet" type="text/css" />
 </head>
 <body>
   <div style="height:998px;">
    <img src="images/bg004.jpg" />
     <div class="class1">
         <div class="class2"></div>
         <div class="class2"></div>
    </div>
    <div class="Areas">
         <div class="Area"><a href="index.html"></a></div>
         <div class="Area"><a href="index.html"></a></div>
         <div class="Area"><a href="index.html"></a></div>
    </div>
   </div>
  </body>
</html>

我想要这个结果:

<html>
 <head>
  <title></title>
  <link href="css.css" rel="stylesheet" type="text/css" />
 </head>
 <body>
   <div style="height:998px;">
    <img src="images/bg004.jpg" />
     <div class="class1">
         <div class="class2"></div>
         <div class="class2"></div>
    </div>
    <div class="Areas">

    </div>
   </div>
  </body>
</html>

谢谢您帮忙

UPDATE

如何做同样的事情,但是我的文件现在是xml?

我测试一下:

    copy("temp/page".$y.".xhtml", "/temp/page".$y.".xml");
$dom = new DOMDocument;
$dom->load( "temp/page".$y.".xml" );
$xpath = new DOMXPath( $dom );
$pDivs = $xpath->query(".//div[@class='Area']");
foreach ( $pDivs as $div ) {
    $div->parentNode->removeChild( $div );
}
$dom->savexml();

我现在有

<?xml version="1.0" encoding="utf-8"?>
<html>
 <head>
  <title></title>
  <link href="css.css" rel="stylesheet" type="text/css" />
 </head>
 <body>
   <div style="height:998px;">
    <img src="images/bg004.jpg" />
     <div class="class1">
         <div class="class2"></div>
         <div class="class2"></div>
    </div>
    <div class="Areas">
         <div class="Area"><a href="index.html"></a></div>
         <div class="Area"><a href="index.html"></a></div>
         <div class="Area"><a href="index.html"></a></div>
    </div>
   </div>
  </body>
</html>

解决方法:

你已经快到了.您只需要将Areas更改为Area,然后使用saveHtmlFile而不是saveHTML:

$dom = new DOMDocument;
$dom->loadHTMLFile( "temp/page".$y.".xhtml" );
$xpath = new DOMXPath( $dom );
$pDivs = $xpath->query(".//div[@class='Area']");
foreach ( $pDivs as $div ) {
  $div->parentNode->removeChild( $div );
}
$dom->saveHTMLFile("temp/page".$y.".xhtml");

这是假设您要将HTML保存回原始文档.请注意DOMXPath会在您的文档顶部添加一个文档类型,我认为可以吗?

标签:html,removeclass,php,dom
来源: https://codeday.me/bug/20191009/1877985.html