php数组读取文本文件

时间:2012-05-27 11:53:13

标签: php arrays file text

  

可能重复:
  Text file lines into array with PHP

如何替换此

$streams = array(
"name1", 
"name2", 
"name3", 
"name4", 
"name5", 
"name6",
);

类似

$streams = array(
streams.txt
);

其中streams.txt包含

"name1", 
"name2", 
"name3", 
"name4", 
"name5", 
"name6",

基本上,整个代码的作用是从该数组中读取这些名称,如果流在线则检查justin.tv。下面是我尝试修复它的所有代码。

<?
$chan = "";
$streams = file('streams.txt');
echo "Live User Streams: ";
foreach ($streams as &$i) {
    $chan = "http://api.justin.tv/api/stream/list.json?channel=" . $i;
    $json = file_get_contents($chan);
    $exist = strpos($json, 'name');
    if($exist) {
        echo "$i  http://twitch.tv/" . $i . " | ";
    }

}
echo "";
 ?>

2 个答案:

答案 0 :(得分:2)

file()函数似乎就是你想要的。

$lines = file("streams.txt");

您可能需要稍微按下输入文本,或者在将线条吸入数组后对其进行后处理。

更新:

这是一个可在我的工作站上运行的命令行示例:

[ghoti@pc ~]$ cat streams.txt 
one
two
three
[ghoti@pc ~]$ php -r '$a = file("streams.txt"); print_r($a);'
Array
(
    [0] => one

    [1] => two

    [2] => three

)
[ghoti@pc ~]$ 

答案 1 :(得分:0)

您需要阅读文件的内容(您可以使用file_get_content),然后使用explode将其转换为数组。