如何用2个文件html替换XPath节点

时间:2015-07-01 12:37:37

标签: php dom xpath domxpath

我需要找到(在originalFile.html(// * [@ id ='divLinkHeader'] / ul))并用新文件(of 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>

1 个答案:

答案 0 :(得分:0)

它不是最优雅的,但它有效

sudo wget -qO- https://get.docker.com/ | sh