Skip to content Skip to sidebar Skip to footer

Find An Element By Id And Replace Its Contents With Php

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,

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

Solution 2:

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

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

Post a Comment for "Find An Element By Id And Replace Its Contents With Php"