按id查找元素并用php替换其内容

Chr*_*ong 4 html php replace preg-replace savechanges

我想使用PHP在文件内容中搜索具有特定id的元素,替换其内容,然后将我的更改保存到文件中.我可以加载HTML,然后再将其保存回来,但是我遇到了'find and replace'(目前正在尝试使用preg_replace)的问题.

这是我到目前为止所拥有的:

<?php
// read in the content
$file = file_get_contents('file.php');

// parse $file, looking for the id.
$replace_with = "id='" . 'myID' . "'>" . $replacement_content . "<";
if ($updated = preg_replace('/id\=\"myID\"\>.*?\</', $replace_with, $file)) {   
    // write the contents of $file back to index.php, and then refresh the page.
    file_put_contents('file.php', $updated);
}
Run Code Online (Sandbox Code Playgroud)

但是,虽然它成功加载内容并将其写出来(我已经通过写入单独的文件对其进行了测试),但似乎$ updated实际上并没有改变.

有任何想法吗?

kar*_*m79 10

您可以使用PHP DOMDocument:

$html = new DOMDocument(); 
$html->loadHTMLFile('file.php'); 
$html->getElementById('myId')->nodeValue = 'New value';
$html->saveHTMLFile("foo.html");
Run Code Online (Sandbox Code Playgroud)