【问题标题】:Fetch content of all div with same class using PHP Simple HTML DOM Parser使用 PHP Simple HTML DOM Parser 获取具有相同类的所有 div 的内容
【发布时间】:2019-12-22 20:15:27
【问题描述】:

我是使用 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; 
?>

【问题讨论】:

    标签: php dom simple-html-dom


    【解决方案1】:

    在您的示例代码中,您有

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

    当您使用第二个参数 1 调用 find() 时,这只会返回 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>
    

    【讨论】:

    • 感谢 Nigel 的宝贵意见,但正如您在本网站的源代码中看到的那样,有三个

      添加代码时会返回这 3 个类的两个内容的 h2。请求您帮助解决我提到的疑问。提前致谢

    • 我刚刚添加了完整的代码和 3 个类的输出。
    • 我不知道先生为什么最后它没有像您提到的那样提供输出。输出为

      为您服务

      让我们取得联系!

      第一个不知何故不见了
    • 我想这里没有办法分享屏幕截图,否则我会分享给你屏幕截图,它仍然提供三分之二的内容。
    • 先生,我发现最后两个

      只有 class="section-heading" 而第一个有两个 class="section-heading text-white" 它是否正在创建任何关心,如果可能的话,请先生帮助您的意见。

    猜你喜欢
    • 2018-05-11
    • 1970-01-01
    • 2011-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-12
    • 2012-04-08
    相关资源
    最近更新 更多