Curl examples with PHP

1. Fetch JSON

Using Jsontest, a public REST API, http://www.jsontest.com/

1
2
3
4
5
6
7
$url = "http://ip.jsontest.com/";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$json = curl_exec($ch);
curl_close($ch);
echo "$json\n";

2. Pass param, return JSON

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
$str = "hey";
$url = "http://md5.jsontest.com/?text=$str";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$json = curl_exec($ch);
curl_close($ch);
echo "$json\n";

// Verify MD5
$md5 = md5($str);
echo "$md5\n";