遍历< div>使用PHP的元素 [英] Loop through <div> elements using PHP

查看:65
本文介绍了遍历< div>使用PHP的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在基本上是div列表的字符串中有一个html块...每个div里面都有要单独解析的html.

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.

我在弄清楚如何遍历初始div时遇到麻烦.

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

任何人都可以帮忙吗?

html的示例:

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

在此示例中,我希望最终代码会循环四次,并为我提供每个div的内容

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

推荐答案

这应该有效(如果HTML在外部文件中):

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

如果包含HTML的字符串,则可以执行以下操作:

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";
}

这将产生:

A
B
C
D

这篇关于遍历&lt; div&gt;使用PHP的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆