How to get file content from URL in PHP

There are various options available to get the content from the URL in PHP. You can get the file content from a remote URL using PHP. PHP file_get_contents() function is the easiest way to parse the content from a web URL.

In the following example code, we will fetch the ads.txt file content from URL in PHP.

$content file_get_contents('https://twitter.com/ads.txt');

If the remote file contains JSON data, use the json_decode() function to convert it into a PHP object.

$data json_decode($content);

To use the file_get_contents() function, the allow_url_fopen directive must be enabled in the PHP configuration file (php.ini). If allow_url_fopen isn’t enabled on your server, use the cURL method to get file content from URL in PHP.

$curl curl_init(); 
curl_setopt($curlCURLOPT_URL'https://twitter.com/ads.txt');
curl_setopt($curlCURLOPT_BINARYTRANSFERtrue);
curl_setopt($curlCURLOPT_RETURNTRANSFERtrue);

$urlData curl_exec($curl);

curl_close($curl);

Leave a reply

keyboard_double_arrow_up