【问题标题】:How to replace a node with XPath, from 2 files html如何用 XPath 替换节点,来自 2 个文件 html
【发布时间】:2015-07-01 12:37:36
【问题描述】:

我需要找到 (in 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>

【问题讨论】:

  • 我不确定你在问什么。你能澄清你的问题吗?
  • 我在您的问题中看到了该代码。我仍然不确定你在问什么。也许减少抽象会有所帮助。这个软件的用途是什么?
  • 我正在处理抓取 URL 的任务。使用 XPath,我可以创建单独的项目(2 个文件 html),但现在我需要将它们组合起来。
  • 我找到了这个解决方案,但它对我不利,因为我有 2 个文件 html link

标签: php dom xpath domxpath


【解决方案1】:

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

$str1 = file_get_contents("originalFile".".html");
$str2 = file_get_contents("otherFile".".html");
$str3 = "abc"; // here Node old

$htmlVar = str_replace($str3, $str2, $str1);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-17
    • 2016-09-17
    • 2021-10-18
    • 2019-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-23
    相关资源
    最近更新 更多