我需要找到(在originalFile.html(//*[@id='divLinkHeader']/ul)中),并用新的(otherFile.html的)替换,因为新文件(originalFile_WithNewUL.html)是用新结构保存的。
<!-- originalFile.html-->
<div class="col-md-4 col-sm-6">
<div id="headerLog" class="call-5">
<a href="#">
<img class="wa333372" src="#">
</a>
</div>
<div id="what5" class="pl-5 subtitle">
</div>
<div id="divLinkHeader" class="sub">
<ul class="list-inline list-unstyled"> <!-- <========= DELETE <ul> ?? -->
<li><a href="#">Line 1</a></li>
<li><a href="#">Line 2</a></li>
<li><a href="#">Line 3</a></li>
<li><a href="#">Line 4</a></li>
</ul>
</div>
</div>
这是另一个文件
<!-- otherFile.html-->
<ul class="list-inline list-unstyled">
<li><a href="#">New Line 1</a></li>
<li><a href="#">New Line 2</a></li>
<li><a href="#">New Line 3</a></li>
</ul>
我只想替换另一个节点来保存一个名为"originalFile_WithNewUL.html"的文件
这是我的代码:
// ---
// Create New originalFile_WithNewUL.html
// ---
$newFile = "originalFile_WithNewUL".".html";
$html = file_get_contents("originalFile".".html");
$dom = new DOMDocument();
@$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
////
////// create the new node from otherFile.html ???
//// $newNode = $dom->createElement('otherFile.html'); ?????
////
////// fetch and replace the old element ?????
//// $oldNode = $xpath->evaluate("//*[@id='divLinkHeader']/ul");
////
//// $results = $xpath->evaluate("//*");
////
$htmlVar = "<!-- WithNewUL -->'n";
$htmlVar = $htmlVar . $dom->saveHTML($results->item(0)) . "'n";
$htmlVar = $htmlVar . "<!-- END WithNewUL -->";
$fid=fopen($newFile,"w+");
fwrite($fid, $htmlVar);
fclose($fid);
我需要创建这个结构
<div class="col-md-4 col-sm-6">
<div id="headerLog" class="call-5">
<a href="#">
<img class="wa333372" src="#">
</a>
</div>
<div id="what5" class="pl-5 subtitle">
</div>
<div id="divLinkHeader" class="sub">
<ul class="list-inline list-unstyled">
<li><a href="#">New Line 1</a></li>
<li><a href="#">New Line 2</a></li>
<li><a href="#">New Line 3</a></li>
</ul>
</div>
</div>
它不是最优雅的,但它可以
$str1 = file_get_contents("originalFile".".html");
$str2 = file_get_contents("otherFile".".html");
$str3 = "abc"; // here Node old
$htmlVar = str_replace($str3, $str2, $str1);