Reputation: 5
#input url
$url = 'http://www.example.com';
#get the data
$json = file_get_contents($url);
$contents = utf8_encode($json);
#convert to php array
$php_array = json_decode($json);
var_dump($php_array);
exit;
I'm trying to decode a website but once I decode it my page comes up as NULL, does anyone know how I can fix it? Thanks
Upvotes: 0
Views: 92
Reputation: 16117
You can use CURL request here:
Example:
<?php
$url = 'http://www.example.com'; // your url
$ch = curl_init(); // initiate
curl_setopt($ch, CURLOPT_URL,$url); // curl url
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$result = curl_exec($ch); // curl output
$php_array = json_decode($result,true);
var_dump($php_array);
?>
Output:
array(3) { ["timestamp"]=> string(8) "10:38:38" ["error_num"]=> int(404) ["error_msg"]=> string(20) "File Not Found Error" }
CURL give you more options to fetch remote content and error checking than to file_get_content.
Upvotes: 0
Reputation: 7080
In your case http://www.example.com this URL returns 404 error. so file_get_contents($url)
get null
value.
$url = 'http://www.example.com';
$json = file_get_contents($url); // HTTP 404
echo $json; //returns null
This works fine
<?php
$url = 'http://www.example.com';
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, $url);
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
$php_array = json_decode($output, true); // true for returning to an array
echo "<pre>";
print_r($php_array);
echo "</pre>";
Extra Tip:
I too faced null
issue sometimes. You could ask json_last_error()
to get definite information.
Upvotes: 2