【问题标题】:Trouble writing results in a csv file在 csv 文件中写入结果时遇到问题
【发布时间】:2019-02-20 23:56:22
【问题描述】:

我在php 中编写了一个脚本来获取链接并将它们写入来自维基百科主页的 csv 文件。该脚本会相应地获取链接。但是,我无法将填充的结果写入 csv 文件。当我执行我的脚本时,它什么也不做,也没有错误。任何帮助将不胜感激。

到目前为止我的尝试:

<?php
include "simple_html_dom.php";
$url = "https://en.wikipedia.org/wiki/Main_Page";
function fetch_content($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();
    foreach ($dom->find('a') as $link) {
        $links[]= $link->href . '<br>';
    }
    return implode("\n", $links);

    $file = fopen("itemfile.csv","w");
    foreach ($links as $item) {
        fputcsv($file,$item);
    }
    fclose($file);
}
fetch_content($url);
?>

【问题讨论】:

  • 为什么要在写入 CSV 文件时添加&lt;br&gt;

标签: php csv curl web-scraping


【解决方案1】:

1.您在函数中使用了return,这就是为什么文件中没有写入任何内容,因为此后代码停止执行。

2.使用以下代码简化您的逻辑:-

$file = fopen("itemfile.csv","w");
foreach ($dom->find('a') as $link) {
  fputcsv($file,array($link->href));
}
fclose($file);

所以完整的代码需要是:-

<?php

   //comment these two lines when script started working properly
    error_reporting(E_ALL);
    ini_set('display_errors',1); // 2 lines are for Checking and displaying all errors
    include "simple_html_dom.php";
    $url = "https://en.wikipedia.org/wiki/Main_Page";
    function fetch_content($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("itemfile.csv","w");
        foreach ($dom->find('a') as $link) {
            fputcsv($file,array($link->href));
        }
        fclose($file);
    }
    fetch_content($url);
?>

【讨论】:

  • @asmitu 很高兴为您提供帮助 :):)
【解决方案2】:

文件没有被写入的原因是你return在代码执行之前退出了函数。

【讨论】:

    猜你喜欢
    • 2021-11-27
    • 2013-12-14
    • 1970-01-01
    • 1970-01-01
    • 2016-05-23
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多