Find an element by id and replace its contents with php

隐身守侯 提交于 2019-11-27 07:05:47

问题


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

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?


回答1:


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");



回答2:


just thinking why are you escaping "=", it should be /id=\"myID\"\>.*?\</




回答3:


I think you have some escaping issues going on ;-)

try this:

$replace_with = 'id="myID">' . $replacement_content . '</';
if ($updated = preg_replace('#id="myID">.*?</#Umsi', $replace_with, $file)) {   
    // write the contents of $file back to index.php, and then refresh the page.
    file_put_contents('file.php', $updated);
}


来源:https://stackoverflow.com/questions/4350141/find-an-element-by-id-and-replace-its-contents-with-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!