如何在不下载文件的情况下将在线CSV文件数据用作值

时间:2012-08-23 20:42:01

标签: c# php

您好我有一个下载CSV文件的链接,我想使用里面的数据来构建我的网站,但我不会下载文件,无论如何要做到这一点? 链接是:http://www.nasdaq.com/screening/companies-by-name.aspx?letter=0&exchange=nasdaq&render=download

5 个答案:

答案 0 :(得分:2)

您需要获取文件以获取其中的数据。

让服务器事后删除它。

答案 1 :(得分:1)

您可以使用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现在将包含该文件的内容。

答案 2 :(得分:0)

使用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.

答案 3 :(得分:0)

您使用的是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现在包含文件的内容。

答案 4 :(得分:0)

这是一种通过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();