【问题标题】:Loading CSV from remote file从远程文件加载 CSV
【发布时间】:2015-09-30 08:18:48
【问题描述】:

我正在从 CSV 编写以下代码来获取股票数据,当我下载了字符串后,它会按以下方式拆分它

<COMPANY NAME>,<STOCK PRICE>,<STOCK CHANGE>
<COMPANY2 NAME>,<STOCK PRICE2>,<STOCK CHANGE2>

我尝试使用 PHP 函数 explode 使用 /n 字符来拆分数组。但是,这并没有正确拆分它。这是我的代码:

public function getQuotes()
{        
    $result = array();      
    $format = $this->format;
    $stockString = "";

    foreach ($this->stocks as $stock)
    { 
        $stockString = $stockString . $stock . "+";
    } 
    //Remove the last "+"
    $stockString = substr($stockString,0,strlen($stockString)-1);
    $s = file_get_contents("http://finance.yahoo.com/d/quotes.csv?s=". $stockString . "&f=" . $format . "&e=.csv");

    //The splitting is to be done here.

    }
}

提前谢谢你

【问题讨论】:

  • 你试过正则表达式吗?

标签: php arrays csv


【解决方案1】:

使用file 函数而不是file_get_contents - 它会为您拆分内容,正如php manual 所说:

以数组形式返回文件。数组的每个元素对应于 文件中的一行,仍然附加换行符。失败后, file() 返回 FALSE。

那么你可以对数组的每个元素使用str_getcsv来获取字段值。

public function getQuotes()
{        
    $result = array();      
    $format = $this->format;
    $stockString = "";

    foreach ($this->stocks as $stock)
    { 
        $stockString = $stockString . $stock . "+";
    } 
    //Remove the last "+"
    $stockString = substr($stockString,0,strlen($stockString)-1);
    $s = file("http://finance.yahoo.com/d/quotes.csv?s=". $stockString . "&f=" . $format . "&e=.csv");

    foreach($s as $line) {
        $values = str_getcsv($line);
    }
}

【讨论】:

    猜你喜欢
    • 2014-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多