【发布时间】: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 文件时添加
<br>?
标签: php csv curl web-scraping