1

I would like to get the value of "Records"

When is try this code:

$json = file_get_contents('URL');
var_dump($json);

This is the result:

string(25289) "{ "ProductsSummary": { "Records": 10, "TotalRecords": 2874, "TotalPages": 288, "CurrentPage": 1 }, "Products": [ { "...

When I try this code

$json = file_get_contents('URL');
$obj = json_decode($json);

echo $obj;
echo $obj->{'ProductsSummary'}->{'Records'};
echo $obj->ProductsSummary->Records;
echo $obj[0]->ProductsSummary->Records;
echo $obj->ProductsSummary[0]->Records;
echo $obj->ProductsSummary[1];

The Output is:

{ "ProductsSummary": { "Records": 10, "TotalRecords": 2879, "TotalPages": 288, "CurrentPage": 1 }, "Products": [ { "Last.... }

Notice: Trying to get property of non-object in  ...
Notice: Trying to get property of non-object in  ...
Notice: Trying to get property of non-object in  ...
Ben Spi
  • 816
  • 1
  • 11
  • 23
  • 1
    What does the question title have to do with the question body? What are you asking exactly? In HTML, carriage returns are ignored by default. That fact has nothing to do with JavaScript or JSON. – Álvaro González Jul 26 '14 at 07:36
  • You need to show us the code that gives you the error message for us to know what you are doing wrong. – Quentin Jul 26 '14 at 07:37
  • 1
    Welcome at SO! It's those "" That's an UTF-8 BOM, most times not welcome, but added by such editors as plain Windows notepad. Check your files with a better editor like notepad++ and convert those files to UTF-8 without BOM. – VMai Jul 26 '14 at 07:38
  • I think this can be true. But I am sending my request to an external API. Thus I have deal with what I get :) – Ben Spi Jul 26 '14 at 10:40
  • i had to get rid of the BOM. You were right. i used this: if(substr($json,0,3) == pack("CCC", 0xEF, 0xBB, 0xBF)) $json = substr($json, 3); – Ben Spi Jul 26 '14 at 15:22
  • Related: https://stackoverflow.com/q/32184933/2943403 – mickmackusa Oct 16 '20 at 06:35

2 Answers2

2

Since you do not have valid JSON, I'm pretty sure that json_decode() is just failing. As per the manual:

Returns the value encoded in json in appropriate PHP type. Values true, false and null are returned as TRUE, FALSE and NULL respectively. NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.

You can verify that with e.g. the is_null() function:

$obj = json_decode($json);
if( is_null($obj) ){
    // Invalid JSON, don't need to keep on working on it
}else{
    // Read data
}

... although the proper way would be to explicitly check for errors with json_last_error(), which should equal JSON_ERROR_NONE unless something went wrong.

If everything works fine, $obj will be an object, thus feeding echo with it will never yield anything useful:

echo $obj;

You might want to use var_dump() instead.

Álvaro González
  • 142,137
  • 41
  • 261
  • 360
0

$json is a string. You should decode it first using json_decode($json)

Ofir
  • 1,565
  • 3
  • 23
  • 41