cURL with PHP to fetch JSON data
I've been fiddling around with PHP and cURL vs. IIS and I finally got to work.
First make sure to remember to add useragent cURL options:
<?php $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, trim($url)); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_USERAGENT, $useragent); $json = curl_exec($ch); curl_close($ch); $json = str_replace('data = ', '', $json); $json = json_decode($json); $json = $json->records; ?>
It's not required, but lets play nice and be the good visitor. Next up is to format the URL correct for the request. I have something like this:
http://example.com/?startdate=1970-01-01 00:00:00&enddate=1970-01-01 23:59:59. Notice the space between the date and the time. Well, this make IIS
very unhappy, and throws me a bad request. So the spaces need to be converted
to a prober URL and we ends up with this:
So remember to encode your URLs correct and you'll be fine.