tags:

views:

98

answers:

2

Hey

I have a block of html in a string that is basically a list of divs... Each div has html inside that I want to parse seperately.

I am having trouble figuring out exactly how to loop over the initial divs.

Can anyone help?

An example of the html:

<div><!-- stuff in here --></div>
<div><!-- stuff in here --></div>
<div><!-- stuff in here --></div>
<div><!-- stuff in here --></div>

In this example I would expect the final code to loop round 4 times and provide me with the contents of each div

+7  A: 

This should work (if the HTML is in an external file):

$doc = new DOMDocument();
$doc->loadHTMLFile('test.html');
$divs = $doc->getElementsByTagName('div');
foreach($divs as $n) {
    echo $n->nodeValue;
}

And in case of a string containing the HTML, you could do:

$doc = new DOMDocument();
$doc->loadHTML('<html><body><div>A</div><div>B</div><div>C</div><div>D</div></body></html>');
$divs = $doc->getElementsByTagName('div');
foreach($divs as $n) {
  echo $n->nodeValue . "\n";
}

which would produce:

A
B
C
D
John Conde
+1 Simply for not mentioning regular expressions. :-)
middaparka
With this, you just need to careful about divs within your divs. Those will be iterated over as well.
Eric Mickelsen
It is an external file, I already seperate out the section I want using strpos and substr, can I do this on a HTML fragment?
Chris
http://php.net/manual/en/domdocument.loadhtml.php
Eric Mickelsen
John, I added a bit to your answer. Normally I would add it as a comment to your answer, but since it was more or less the same as what you yourself already answered, I edited it right away. Of course, if you object, feel free to remove it.
Bart Kiers
Can I make this intolerant to errors? I could paste (externally) the html im trying to parse?
Chris
@Bart K., additions and improvements are always welcome. :) @Chris, you can add error checking to this by verifying their is actually HTML in the string/file to be checked. You can also add HTML right into the loadHTML method just like Bart's example shows.
John Conde
A: 

If it's XHTML, you can use SimpleXML:

$xml = simplexml_load_string($xhtmlstring);
foreach ($xml->div as $d) {
   {
   //parsing
   }
}
Eric Mickelsen
I have tried simple xml but it fails to load unfortunately, im not sure why!
Chris
Try this to output xml errors:libxml_use_internal_errors(true);$sxe = simplexml_load_string("<?xml version='1.0'><broken><xml></broken>");if (!$sxe) { echo "Failed loading XML\n"; foreach(libxml_get_errors() as $error) { echo "\t", $error->message; }}
Eric Mickelsen