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.

2
  • Did you get any result? Are you sure that the numbers are not separated by an other whitespace character, like a tab? Commented May 2, 2011 at 9:57
  • When I used the "\n" I got the result. Commented May 2, 2011 at 13:06

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

Comments

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()

Comments

0

Try exploding at "\n"

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

Also have a look at:

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

Comments

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.