How to get URL contents using PHP

02 Dec 2018 • 1 min read

There are a lot of ways on how to get the content of a URL page in PHP. But there are two common or easiest ways on how to read page contents and that is by using the file() or file_get_contents() functions.

The file() function will a return the contents of a file or url 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. And 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:


The `file_get_contents()` function is just like `file()` function but the difference is that the `file_get_contents()` function will return a string instead of 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.


But if you want to have a result in an array 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 params will not work on remote files/URLs.

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.

Mervin Villaceran 👱🏻

is a Filipino Software Developer who continues to learn new things. 👨🏼‍💻