【问题标题】:Can't write different items in different columns in a csv file无法在 csv 文件的不同列中写入不同的项目
【发布时间】:2018-09-17 11:23:21
【问题描述】:

我在php 中编写了一个脚本来抓取不同的title 帖子及其links,并将它们从网页写入一个csv 文件。我希望在column A 中写titles 及其相关的linkscolumn B 中。当我将它们写在单个列中时,脚本就可以完成这项工作。但是,由于我不知道如何在多列中写入数据,所以我卡住了。

目前它正在将 titles 写入 csv 文件,因为我已经在脚本中注释掉了 links 部分,只是因为我不知道如何在 column B 中编写它们。任何解决问题的帮助将不胜感激。

这是我尝试过的:

<?php
    include "simple_html_dom.php";
    $url = "https://stackoverflow.com/questions/tagged/web-scraping";
    function get_information($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
        $htmlContent = curl_exec($ch);
        curl_close($ch);
        $dom = new simple_html_dom();
        $dom->load($htmlContent);
        $links = array();
        $file = fopen("outputfile.csv","w");
        foreach ($dom->find('.question-hyperlink') as $link) {
            fputcsv($file,array($link->innertext));
            //fputcsv($file,array($link->href));
        }
        fclose($file);
    }
    get_information($url);
?>

【问题讨论】:

    标签: php csv curl dom web-scraping


    【解决方案1】:

    试试这个代码

    <?php
        include "simple_html_dom.php";
        $url = "https://stackoverflow.com/questions/tagged/web-scraping";
        function get_information($url)
        {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
            $htmlContent = curl_exec($ch);
            curl_close($ch);
            $dom = new simple_html_dom();
            $dom->load($htmlContent);
            $links = array();
            $file = fopen("outputfile.csv","w");
            foreach ($dom->find('.question-hyperlink') as $link) {
                fputcsv($file,[$link->innertext,$link->href]);
            }
            fclose($file);
        }
        get_information($url);
    ?>
    

    【讨论】:

    • 您能对您的代码添加一些解释吗?这样 OP 才能更好地理解。
    • 感谢@Jignesh Joisar,为您提供解决方案。它工作得很好。顺便说一句,如何剥离php 中的字符串以排除不需要的空间?
    • @asmitu 使用 trim() 和 str_replace() 函数删除不需要的空间
    猜你喜欢
    • 2020-01-15
    • 2020-11-18
    • 1970-01-01
    • 2018-11-01
    • 2012-03-30
    • 2015-11-12
    • 2021-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多