Find an element by id and replace its contents with php(通过 id 查找元素并用 php 替换其内容)
问题描述
我想使用 PHP 在文件内容中搜索具有特定 ID 的元素,替换其内容,然后将更改保存到文件中.我能够加载 HTML,然后再次将其保存,但是在查找和替换"(目前正在尝试使用 preg_replace)时遇到问题.
I want to use PHP to search through the contents of a file for an element with a specific id, replace its contents, then save my changes to the file. I'm able to load in the HTML, and save it back out again, but am having trouble with the 'find and replace' (currently trying to use 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);
}
然而,虽然它成功加载内容并将其写出(我已经通过写入单独的文件对其进行了测试),但似乎 $updated 实际上并没有改变.
However, while it successfully loads in the content and writes it out (I've tested it by writing to a separate file), it appears that $updated doesn't actually change.
有什么想法吗?
推荐答案
你可以使用 PHP 的 DOMDocument
为此:
You can use PHP's DOMDocument
for this:
$html = new DOMDocument();
$html->loadHTMLFile('file.php');
$html->getElementById('myId')->nodeValue = 'New value';
$html->saveHTMLFile("foo.html");
这篇关于通过 id 查找元素并用 php 替换其内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:通过 id 查找元素并用 php 替换其内容


- 从 PHP 中的输入表单获取日期 2022-01-01
- 没有作曲家的 PSR4 自动加载 2022-01-01
- 正确分离 PHP 中的逻辑/样式 2021-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- PHP Count 布尔数组中真值的数量 2021-01-01
- SoapClient 设置自定义 HTTP Header 2021-01-01
- 如何定位 php.ini 文件 (xampp) 2022-01-01
- Laravel 仓库 2022-01-01
- Mod使用GET变量将子域重写为PHP 2021-01-01
- 带有通配符的 Laravel 验证器 2021-01-01