【问题标题】:php array read text file [duplicate]php数组读取文本文件[重复]
【发布时间】:2012-05-27 11:53:13
【问题描述】:

可能重复:
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 "";
 ?>

【问题讨论】:

  • 文本文件是您自己生成的吗?如果是这样,请不要尝试使其成为“半个数组”。只需在每一行上使用一个普通名称(不带引号和逗号)并将它们读入一个数组。
  • 根据您的编辑,如果这是您使用streams.txt 中每一行的方式,并且streams.txt 看起来像您在上面发布的内容,那么很明显为什么会失败。清理streams.txt,并进行一些调试——使用print_r() 来查看$streams 中的内容,并回显$chat 来查看您实际尝试获取的内容。哦,不要使用short tags

标签: php arrays file text


【解决方案1】:

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 ~]$ 

【讨论】:

  • $streams = file('streams.txt');没用
  • 它做了什么?它在什么方面不起作用?
  • 没有一个流显示为在线。我已将所有代码添加到第一篇文章中。
  • 不适合我。另外我的目标是永远不必再接触 .php 文件,只需将新的流媒体添加到 .txt 文件中。
【解决方案2】:

你需要读取文件的内容(可以使用file_get_content),然后使用explode把它变成一个数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-09
    • 2016-04-23
    • 2011-07-08
    • 1970-01-01
    相关资源
    最近更新 更多