通过 id 查找元素并用 php 替换其内容 [英] Find an element by id and replace its contents with php

查看:41
本文介绍了通过 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 替换其内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆