我正在拉入CSV,我想根据新行爆炸返回的字符串。
$quotes = file_get_contents('http://ca.finance.yahoo.com/d/quotes.csv?s=CLQ12.NYM+NGQ12.NYM+GCQ12.CMX+SIN12.CMX+HGN12.CMX+^DJI+^GSPC+^GSPTSE+^SPCDNX+X&f=nsc1');
给我:
"Crude Oil Aug 12","CLQ12.NYM",-3.10
"Natural Gas Aug 1","NGQ12.NYM",-0.165
"Gold Aug 12","GCQ12.CMX",-28.40
"Silver Jul 12","SIN12.CMX",-0.698
"Copper Jul 12","HGN12.CMX",-0.079
"S&P 500","^GSPC",-13.20
"S&P/TSX Composite","^GSPTSE",-156.71
"S&P/TSX Venture C","^SPCDNX",-18.29
"United States Ste","X",-0.37
但是,使用$quotes = explode('\n', $quotes);
无效。什么是返回每行数组的最简单方法?
答案 0 :(得分:8)
您需要双引号,否则PHP将无法解析转义序列:
$quotes = explode("\n", $quotes);
您还可以使用file()
返回一行数组:
$array = file( 'http://ca.finance.yahoo.com/d/quotes.csv?s=CLQ12.NYM+NGQ12.NYM+GCQ12.CMX+SIN12.CMX+HGN12.CMX+^DJI+^GSPC+^GSPTSE+^SPCDNX+X&f=nsc1');
但是,更好的方法可能是PHP内置的CSV函数,例如fgetcsv()
。
答案 1 :(得分:1)
答案 2 :(得分:0)
我宁愿使用PHP_EOL来实现跨操作系统兼容性:
<?php
$quotes = file_get_contents('http://ca.finance.yahoo.com/d/quotes.csv?s=CLQ12.NYM+NGQ12.NYM+GCQ12.CMX+SIN12.CMX+HGN12.CMX+^DJI+^GSPC+^GSPTSE+^SPCDNX+X&f=nsc1');
$lines = explode(PHP_EOL, $quotes);
?>