Loop through <div> elements using PHP

烈酒焚心 提交于 2020-01-01 19:27:09

问题


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


回答1:


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



回答2:


If it's XHTML, you can use SimpleXML:

$xml = simplexml_load_string($xhtmlstring);
foreach ($xml->div as $d) {
   {
   //parsing
   }
}


来源:https://stackoverflow.com/questions/2089258/loop-through-div-elements-using-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!