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

The above code prints an array as an output.

If I use

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

However it does not display individual numbers in the text file in the form of an array.

Ultimately I want to read numbers from a text file and print their frequency. The data.txt has 100,000 numbers. One number per line.

5 Answers5

8

A new line is not a space. You have to explode at the appropriate new line character combination. E.g. for Linux:

explode("\n",$homepage)

Alternatively, you can use preg_split and the character group \s which matches every white space character:

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

Another option (maybe faster) might be to use fgetcsv.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
5

If you want the content of a file as an array of lines, there is already a built-in function

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

See Manual: file()

KingCrunch
  • 128,817
  • 21
  • 151
  • 173
0

Try exploding at "\n"

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

Also have a look at:

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

Yoshi
  • 54,081
  • 14
  • 89
  • 103
0

You could solve it by using a Regexp also:

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

This will give you the variable $matches which contains an array with numbers. This will ensure it will only retrieve lines that have numbers in them in case the file is not well formatted.

rzetterberg
  • 10,146
  • 4
  • 44
  • 54
0

You are not exploding the string using the correct character. You either need to explode on new line separator (\n) or use a regular expression (will be slower but more robust). In that case, use preg_split

KingCrunch
  • 128,817
  • 21
  • 151
  • 173
Vincent Mimoun-Prat
  • 28,208
  • 16
  • 81
  • 124