Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Get Contents of a URL or Page

Tags:

html

php

curl

I am trying to create a PHP script which can request data, such as HTML content, from an external server, then do something with the received content. Here is a generalized example of what I am trying to accomplish:

//Get the HTML generated by http://api.somesite.com/

//Now tack on the Unix timestamp of when the data was received
$myFetchedData = $dataFromExternalServer . "\n Data received at: ". time();

echo $myFetchedData;

I'm thinking I should use curl in here somewhere, but I am not sure after that. Could someone post a generalized example of how I could do this?

like image 293
Oliver Spryn Avatar asked May 11 '11 22:05

Oliver Spryn


2 Answers

If you only need GET and allow_url_fopen is enabled on your server, you can simply use

$data = file_get_contents('http://api.somesite.com');
like image 60
ThiefMaster Avatar answered Oct 31 '22 02:10

ThiefMaster


simple methods

<?php
echo readfile("http://example.com/");   //needs "Allow_url_include" enabled
//OR
echo include("http://example.com/");    //needs "Allow_url_include" enabled
//OR
echo file_get_contents("http://example.com/");
//OR
echo stream_get_contents(fopen('http://example.com/', "rb")); //you may use "r" instead of "rb"  //needs "Allow_url_fopen" enabled
?> 

The best Way (using cURL):

echo get_remote_data('http://example.com');   //SIMPLE REQUEST;
//OR
echo get_remote_data('http://example.com', "var2=something&var3=blabla" ); //POST REQUEST;

(CODE: at GitHub )

like image 40
T.Todua Avatar answered Oct 31 '22 02:10

T.Todua