Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP explode function with file_get_contents?

Tags:

php

explode

   <?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 Answers

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.

like image 134
Felix Kling Avatar answered Mar 04 '26 18:03

Felix Kling


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

like image 42
KingCrunch Avatar answered Mar 04 '26 17:03

KingCrunch