ASH
ASH

Reputation: 253

how to properly load json in php?

I've tried other SO pages but can't find a solution.

I have a json file that i'm trying to import into a php file but it returns NULL.

The json on my web server is valid and yet no luck.

http://higconsolidated.com/json.json

PHP file:

$json = file_get_contents('http://higconsolidated.com/json.json');
$obj = json_decode($json);
var_dump($obj);

Error log:

file_get_contents(higconsolidated.com/json.json): failed to open stream: Connection refused in getjson.php

Thanks in advance.

Upvotes: 2

Views: 75

Answers (4)

CaringDev
CaringDev

Reputation: 8551

In your PHP you are using json.json instead of json.php. Probably json.json doesn't exist.

After your update: For me, having a file

<?php
  $json = file_get_contents('http://higconsolidated.com/json.json');
  $obj = json_decode($json);
  var_dump($obj);
?>

yields array(47) { [0]=> object(stdClass)#1 (5) { ["code"]=> string(4) "1031" ["par"]=> string(1) "1" ["category"]=> string(1) "A" ["product"]=> string(18) "FIDJI QUINOA SALAD" ["format"]=> string(5) "2x1kg" } [1]=>...

In case you have additional code, please try using the above minimal file.

After second update: Your problem has nothing to do with parsing JSON. It seems you run into some kind of request / traffic limit or firewall issue. Is higconsolidated.com the same host you are running your PHP file on?

Upvotes: 2

Amit.S
Amit.S

Reputation: 441

$json = file_get_contents('http://higconsolidated.com/json.json');
$obj = json_decode($json);
foreach ($obj as $value) 
{
    //you can retrieve all the keys here
    echo $value->code."<br>" ;
}

Upvotes: 0

GiDar
GiDar

Reputation: 143

Your approach is right, but let me suggest you to check the format of the json file you are using.

<?php

// the following strings are valid JavaScript but not valid JSON

// the name and value must be enclosed in double quotes
// single quotes are not valid 
$bad_json = "{ 'bar' : 'baz' }";
json_decode($bad_json); // null

// the name must be enclosed in double quotes
$bad_json = '{ "bar" : "baz" }';
json_decode($bad_json); // null

// trailing commas are not allowed
$bad_json = '{ "bar" : "baz", }';
json_decode($bad_json); // null

?>

Take a look at here http://php.net/manual/en/function.json-decode.php

Upvotes: 0

Disha V.
Disha V.

Reputation: 1864

$json = file_get_contents('http://higconsolidated.com/json.php');

Upvotes: 0

Related Questions