➺  Mervin Villaceran

PHP : How to get URL page contents

December 2, 2018 1 min read
PHP

There are two ways on how to read URL page contents in PHP and that is by using file() and file_get_contents() functions.

The file() function will return the contents of a url or a file into an array.

Syntax:

array file ( string $filename [, int $flags = 0 [, resource $context ]] )

Example:

<?php

$arrayLines = file('https://www.w3schools.com');

This function will return an array of strings. But if you want to get the result into a single string then you can use the implode() function to combine the array.

Example:

<?php

$arrayLines = file('https://www.w3schools.com');
echo implode('', $arrayLines);

And you will get this result:

While the file_get_contents() function will return a string instead of an array.

Syntax:

string file_get_contents ( string $filename [, bool $use_include_path = FALSE [, resource $context [, int $offset = 0 [, int $maxlen ]]]] )

Example:

<?php

$str = file_get_contents('https://www.w3schools.com');
echo $str;

This example will output just like the above example.

If you want an array result using this function, you can use the explode() function to split the string using the newline(\n) character as a delimiter.

<?php

$str = file_get_contents('https://www.w3schools.com');
$arrayLines = explode('\n', $str);
var_dump($arrayLines);

Note that the offset and maxlen parameters will not work on remote URLS/files.

So the difference between the two is that the file() function will return an array by parsing EOL (end-of-line) characters, but each strings in the array will still have the terminating newline attached to the end of the string. While the file_get_contents() function will just return a single string that will also have a terminating newline.

Danke! Ciao!