无法在csv文件的不同列中写入不同的项目

问题描述 投票:0回答:1

我在php写了一个脚本来刮掉不同的title帖子及其links并将它们写入网页的csv文件。我想在titlescolumn A及其在links的相关column B。当我将它们写在一个列中时,该脚本可以完成这项工作。但是,由于我不知道如何在多列中写入数据,因此我陷入困境。

目前它正在csv文件中编写titles,因为我已经在脚本中注释了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个回答
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);
?>
© www.soinside.com 2019 - 2024. All rights reserved.