【发布时间】:2012-08-23 20:42:01
【问题描述】:
您好,我有一个下载 CSV 文件的链接,我想使用里面的数据来建立我的网站,但我不会下载文件,有什么办法吗? 链接是:http://www.nasdaq.com/screening/companies-by-name.aspx?letter=0&exchange=nasdaq&render=download
【问题讨论】:
您好,我有一个下载 CSV 文件的链接,我想使用里面的数据来建立我的网站,但我不会下载文件,有什么办法吗? 链接是:http://www.nasdaq.com/screening/companies-by-name.aspx?letter=0&exchange=nasdaq&render=download
【问题讨论】:
您需要获取文件才能获取其中的数据。
之后让您的服务器将其删除。
【讨论】:
WebClient.OpenRead() 打开文件流并将结果分配给流(见我的回答)。然而,这是 C#。
您可以在运行时使用 cURL 获取文件的内容。
$url = "http://www.nasdaq.com/screening/companies-by-name.aspx?letter=0&exchange=nasdaq&render=download";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$data = curl_exec($ch);
curl_close($ch);
$data 现在将包含该文件的内容。
【讨论】:
curl_init() 未定义,则表示您的服务器上未安装 PHP cURL 库。如果您不能/不想安装它,请尝试使用 Stegrex 的 fopen() 解决方案。
使用 fopen() 或 PHP cURL 库:
fopen() (通常这不如 cURL 安全,当 PHP 设置文件中不允许使用 fopen 时,您可能会遇到问题,但这是一种快速而肮脏的方法):
// Load file into resource from URL.
$fileHandle = fopen("http://www.nasdaq.com/screening/companies-by-name.aspx?letter=0&exchange=nasdaq&render=download", "r");
// Edit: Load file resource into string.
$fileContents = fread($fileHandle);
echo $fileContents;
cURL(首选方式。在此处阅读 cURL:http://php.net/manual/en/book.curl.php):
$curl = curl_init(); // Open a cURL library resource.
// Set the resource option for the URL.
curl_setopt($curl, CURLOPT_URL, "http://www.nasdaq.com/screening/companies-by-name.aspx?letter=0&exchange=nasdaq&render=download");
// Set the resource option to let it return a value from the execution function.
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$file = curl_exec($curl); // Execute cURL, load the result into variable $file.
curl_close($curl); // Close the cURL resource.
print_r($file); // The file should now be a string, exactly the CSV string that was scraped.
【讨论】:
fopen() 返回一个文件资源,您必须对其进行操作才能获取字符串。在我编辑的答案中使用fread() 并回显该返回值,而不是资源。如果可以的话,我强烈建议您安装 cURL,因为您可以更好地控制安全性等。
您使用的是 C# 还是 PHP?我的解决方案是 C#。
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://www.nasdaq.com/screening/companies-by-name.aspx?letter=0&exchange=nasdaq&render=download");
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
StreamReader reader = new StreamReader(resp.GetResponseStream());
string CSVContents = reader.ReadToEnd();
CSVContents 现在包含文件的内容。
【讨论】:
这是一种通过 Stream 读取数据的方法,而不是将数据内容下载到您的物理磁盘。这是在 C# 中的(不知道你想要 PHP 还是 C#,因为你的标签包含两者)
string uriString = @"http://www.nasdaq.com/screening/companies-by-name.aspx?letter=0&exchange=nasdaq&render=download";
WebClient myWebClient = new WebClient();
Stream myStream = myWebClient.OpenRead(uriString); //open a stream to the resource
StreamReader sr = new StreamReader(myStream);
Console.WriteLine(sr.ReadToEnd()); //print contents of stream
myStream.Close();
【讨论】: