Jump to content

replace div by id using domdocument


davrosboy

Recommended Posts

Hello all

I am trying to replace the contents of a div using its id.

All the regex solutions i have tried will not account for

nested divs, so i think the dom parser is the solution

but so far cannot get it to work, i am learning as i go and not even sure if this is the right

path to take, what i have so far is

 

<?php

$string = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

    "http://www.w3.org/TR/html4/loose.dtd">

<html>

<body> 

<div id="fullcontent">

<div class="leftone"><p>some left text</p></div>

<div class="rightone"><p>some right text</p></div>

</div>

</body>

</html> ';

$postedid = "fullcontent";

$posteddata = '<div id="fullcontent">

<div class="leftone"><p>some new left text</p></div>

<div class="rightone><p>some new right text</p></div>

</div>';

$html = new DOMDocument;

$html->loadHTML($string);

$elements = $html->getElementById($postedid);

$newelement = $html->createTextNode($posteddata);

$elements->parentNode->replaceChild($newelement, $elements);

echo $html->saveHTMLFile("test.html");

$testget = file_get_contents("test.html");

echo $testget;

?>

 

Any help or advice would be appreciated

 

Cheers

Davros

Link to comment
https://forums.phpfreaks.com/topic/174560-replace-div-by-id-using-domdocument/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.