在 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>
感谢您的帮助
更新
如何做同样的事情,但我的文件现在是 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>