首页 > 解决方案 > 使用 PHP Simple HTML DOM Parser 获取具有相同类的所有 div 的内容

问题描述

我是使用 PHP 解析 HTML DOM 的新手,有一个页面包含不同的内容但具有相同的“类”,当我尝试获取内容时,我能够获取最后一个 div 的内容,是否有可能以某种方式我可以获得具有相同课程的所有 div 内容,请您查看我的代码:

<?php
    include(__DIR__."/simple_html_dom.php");
    $html = file_get_html('http://campaignstudio.in/');
    echo $x = $html->find('h2[class="section-heading"]',1)->outertext; 
?>

标签: phpdomsimple-html-dom

解决方案


在您的示例代码中,您有

echo $x = $html->find('h2[class="section-heading"]',1)->outertext; 

当您find()使用第二个参数 1 调用时,这只会返回 1 元素。相反,如果您找到所有这些-您可以对它们做任何您需要的事情...

$list = $html->find('h2[class="section-heading"]');
foreach ( $list as $item ) {
    echo $item->outertext . PHP_EOL;
}

我刚刚测试的完整代码是......

include(__DIR__."/simple_html_dom.php");
$html = file_get_html('http://campaignstudio.in/');

$list = $html->find('h2[class="section-heading"]');
foreach ( $list as $item ) {
    echo $item->outertext . PHP_EOL;
}

这给出了输出......

<h2 class="section-heading text-white">We've got what you need!</h2>
<h2 class="section-heading">At Your Service</h2>
<h2 class="section-heading">Let's Get In Touch!</h2>

推荐阅读