PHP Classes

Replace contents

Recommend this page to a friend!

      HTML Parser  >  All threads  >  Replace contents  >  (Un) Subscribe thread alerts  
Subject:Replace contents
Summary:Is it possible with your class to replace contents?
Messages:4
Author:Mick89
Date:2015-06-25 08:17:29
 

 


  1. Replace contents   Reply   Report abuse  
Picture of Mick89 Mick89 - 2015-06-25 08:17:29
Hello,

Thank you for your work!

Is it possible with your class to replace contents?

For example in '$content':

<h1>my title</h1>
<h2>my title</h2>
<h2>my title</h2>

I would like to replace it with this in '$new_content':

<h1>my title</h1>
<h2>my title</h2>
<h2 id="myID">My title</h2>

Thanks again!
Mick

  2. Re: Replace contents   Reply   Report abuse  
Picture of Dave Smith Dave Smith - 2015-06-25 11:33:48 - In reply to message 1 from Mick89
It is currently just a parser and does not have a method to change or write the data back.

I suppose those methods could be added, however it would not be nearly as efficient working on the returned array as working directly with the object where you would not even need a class...

$doc = new DOMDocument();
$doc = loadHTMLFile("filename.html");
$doc->getElementsByTagName('h2')->item(1)->nodeValue = 'My title';
$doc->getElementsByTagName('h2')->item(1)->setAttribute('id','myID');


I haven't tested that code, but in theory it should change the second instance of the h2 element to reflect the changes in your example. You may even be able to chain the setAttribute and change the nodeValue together on the same line. I have only recently started working with and learning the DOM.

Dave

  3. Re: Replace contents   Reply   Report abuse  
Picture of Dave Smith Dave Smith - 2015-06-25 11:58:53 - In reply to message 2 from Dave Smith
Without fail I have a typo in the above code...

$doc = loadHTMLFile("filename.html");

should be

$doc->loadHTMLFile("filename.html");

  4. Re: Replace contents   Reply   Report abuse  
Picture of Mick89 Mick89 - 2015-06-26 08:32:19 - In reply to message 3 from Dave Smith
You directed me towards a good track.

$doc = new DOMDocument();
$doc->loadHTML($content, LIBXML_HTML_NODEFDTD | LIBXML_HTML_NOIMPLIED);

$elements = $doc->getElementsByTagName( 'h2' );
if($elements instanceof DOMNodeList)
foreach($elements as $domElement)
$domElement->setAttribute('id','myID');

$html = $doc->saveHTML();
print $html;

Thanks again!
Mick

 
For more information send a message to info at phpclasses dot org.