<?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.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With