gpt4 book ai didi

php打开修改并保存html文件

转载 作者:行者123 更新时间:2023-11-28 04:03:56 26 4
gpt4 key购买 nike

在 php 中我想打开一个 html 文件,删除 div(类区域)的内容并保存它。

$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>

谢谢你的帮助

更新

如何做同样的事情,但我的文件现在是一个 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 会将文档类型添加到您的文档的顶部,我想这没问题吧?

关于php打开修改并保存html文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12259785/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com