Skip to content
Advertisement

How to read json file from url in php/laravel?

I want to open a JSON from url in php/laravel file. this is my code :

{{ini_set("allow_url_fopen", 1)}}
{{$id_ = $blog_post->featured_media}}
{{$url_ = 'http://example.net/blog/wp-json/wp/v2/media/'.$id_}}
{{$data = @file_get_contents($url_)}}
{{$json = @json_decode($data, true)}}
{{var_dump(@$json)}}

when i try reload page i get this error :

something went wrong

how can i read JSON from url ?

Advertisement

Answer

Use cURL to get the json data. Like this

$url = 'www.yoururl.com/full-url';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_HTTPHEADER, Array("User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.15) Gecko/20080623 Firefox/2.0.0.15") ); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result= curl_exec ($ch);
curl_close ($ch);
$info = json_decode($result, true); 
print_r($info); // print all data
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement