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 替换其内容


基础教程推荐
- 在多维数组中查找最大值 2021-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01