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

查看:119
本文介绍了通过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).

以下是我到目前为止:

Here's what I have so far:

<?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);
}

然而,当它成功加载内容并写出来(I'已经通过写入一个单独的文件来测试它),它看起来$更新并没有真正改变。

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.

有什么想法?

Any ideas?

推荐答案

您可以使用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天全站免登陆