1

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 url of the page that needs to be edited
  • the id of 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

7
  • 1
    Have you considered seperating your PHP code from your HTML? For example, using some kind of templating language? Seperating the markup from the code could make your problem much simpler - and your future brighter overall. Commented Aug 14, 2014 at 11:17
  • I separate parts of the HTML that occur on different pages, like a header or footer, but I don't with the content of the page that's unique. It's like: PHPfile(PHPheader - HTML content - PHP footer). Is it a bad thing to do? This way I prevent making another document for the content, right? Commented Aug 14, 2014 at 11:22
  • 1
    Incidentally - I'm a little confused why you are getting a -file- from a -URL-. Presumably you're retrieving the file server-side, otherwise it would just be pared PHP (HTML in this case) Commented Aug 14, 2014 at 11:22
  • With JS I get the file url client side and send it to the server. Is there a better way to get the page? Commented Aug 14, 2014 at 11:25
  • It's not about better or worse - it's about if you want to str-replace the interpreted result (the HTML) or if you want to edit the PHP (pre-render). Could you clarify? Commented Aug 14, 2014 at 11:29

1 Answer 1

1

First of all, you are right in not wanting to use a regex function for HTML parsing. See the answer here.

I'm going to answer this question under the presumption you are committed to the idea of retrieving PHP files server-side before they are interpreted. There is an issue with your approach right now, since you seem to be under the impression that you can retrieve the source PHP file by the URL parameter - but that's the location of the result (interpreted PHP). So be careful your structure does what you want.

I am under the assumption that the PHP files are structured like this:

<?php include_some_header(); ?>
    <tag>...</tag>
    <!-- some HTML -->
<?php //some code ?>
    <tag>...</tag>
    <!-- some more HTML -->
<?php //some code ?>

Your problem now is that you cannot use an HTML reader (and writer), since your file is not HTML. My answer is that you should restructure your code, separating templating language from business logic. Get started with some templating language. Afterwards, you'll be able to open the template, without the code, and write back the template using a DOM parser and writer.

Your only alternative in your current setup is to use the replace function as you have found in this answer. It's ugly. It might break. But it's definitely not impossible. Make backups before writing over your own code with your own code.

Sign up to request clarification or add additional context in comments.

2 Comments

Let's get into a templating language! Thanks for your answer! Only thing that's not yet clear is how I get the location of the edited html part that's included when doing this.
That problem should be happening for your PHP file too though! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.