Problem
I'm trying to edit HTML/PHP files server side with PHP. With AJAX Post I send three different values to the server:
- the urlof the page that needs to be edited
- the idof the element that needs to be edited
- the new content for the element
The PHP file I have now looks like this:
<?php
    $data = json_decode(stripslashes($_POST['data']));
    $count = 0;
    foreach ($data as $i => $array) {
        if (!is_array($array) && $count == 0){
            $count = 1;
            // $array = file url
        }
        elseif (is_array($array)) {
            foreach($array as $i => $content){
                // $array[0] = id's
                // $array[1] = contents
            }
        }
    }
?>
As you can see I wrapped the variables in an array so it's possible to edit multiple elements at a time. I've been looking for a solution for hours but can't make up my mind and tell what's the best/possible solution.
Solution
I tried creating a new DOMElement and load in the html, but when dealing with a PHP file, this solution isn't possible since it can't save php files:
$html = new DOMDocument(); 
$html->loadHTMLFile('file.php'); 
$html->getElementById('myId')->nodeValue = 'New value';
$html->saveHTMLFile("foo.html");
(From this answer)
Opening a file, writing in it and saving it comes is another way to do this. But I guess I must be using str_replace or preg_replace this way.
$fname = "demo.txt";
$fhandle = fopen($fname,"r");
$content = fread($fhandle,filesize($fname));
$content = str_replace("oldword", "newword", $content);
$fhandle = fopen($fname,"w");
fwrite($fhandle,$content);
fclose($fhandle);
(From this page)
I read everywhere that str_replace and preg_replace are risky 'caus I'm trying to edit all kinds of DOM elements, and not a specific string/element. I guess the code below comes close to what I'm trying to achieve but I can't really trust it..
$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);
}
(From this answer)
Question
In short: what is the best solution, or is it even possible to edit HTML elements content in different file types with only an id provided?
Wished steps:
- get file from - url
- find element with - id
- replace it's content 
 
     
    