PHP使用file_get_contents爆炸函数?

时间:2011-05-02 09:54:35

标签: php explode

   <?php
$str = "Hello world. It's a beautiful day.";
print_r (explode(" ",$str));
?>

上面的代码打印一个数组作为输出。

如果我使用

<?php
$homepage = file_get_contents('http://www.example.com/data.txt');
print_r (explode(" ",$homepage));
    ?>

但是,它不会以数组的形式在文本文件中显示单个数字。

最终我想从文本文件中读取数字并打印它们的频率。 data.txt有100,000个数字。每行一个数字。

5 个答案:

答案 0 :(得分:5)

新行不是空格。你必须在适当的新行字符组合中爆炸。例如。对于Linux:

explode("\n",$homepage)

或者,您可以使用preg_split和与每个空格字符匹配的字符组\s

preg_split('/\s+/', $homepage);

另一种选择(可能更快)可能是使用fgetcsv

答案 1 :(得分:4)

如果您希望将文件内容作为行数组,则已有内置函数

var_dump(file('http://www.example.com/data.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));

请参阅Manual: file()

答案 2 :(得分:0)

尝试在“\ n”爆炸

print_r (explode("\n",$homepage));

另请看:

http://php.net/manual/de/function.file.php

答案 3 :(得分:0)

您也可以使用Regexp来解决它:

$homepage = file_get_contents("http://www.example.com/data.txt");
preg_match_all("/^[0-9]+$/", $homepage, $matches);

这将为您提供变量$ matches,其中包含带数字的数组。这将确保它只检索包含数字的行,以防文件格式不正确。

答案 4 :(得分:0)

您没有使用正确的字符爆炸字符串。您需要在新行分隔符(\n)上爆炸或使用正则表达式(将更慢但更强大)。在这种情况下,请使用preg_split