访问Json对象PHP(字符串不是数组)

Yes, I have read previous questions and I know how to access a JSON object and how to convert it into an array. I know about json_encode/decode. My problem is that my JSON response has a string, arrays and all and it will always return NULL when I access the data directly.

  object(Unirest\Response)#8 (4) {
    ["code"]=>
      int(200)
    ["body"]=>
      string(666) "{ "ticker": "AAPL:US", ".."
    ["headers"]=>
    array(9) {
    [0]=>
    string(15) "HTTP/1.1 200 OK"

Normally you would be able to directly access the object like this and this worked just fine when I last accessed the script a few days ago:

$response->body->ticker

Or you could use json_decode with true to turn it into an array.

$array = json_decode($response->body, true);

However, all of this no longer works. I believe they changed something with the output because it was working just a while ago but I have no clue. Any idea how to access the ticker data? I tested it with a different API and the same commands are working just fine to retrieve data from a different API, but the output seems to be different.

$response->body is a json string assuming you didnt shorten it so much as to loose someting important and therefore needs to be seperately converted to a PHP data item.

As its a json string representing an object why not convert it to a PHP object like so

$body = json_decode($response->body);

Then you can address its properties like

$body->ticker

Alternatively

$response->body = json_decode($response->body);

Now you can address it as you expected i.e.

$response->body->ticker

Ok, finally solved it after reading this answer: PHP json_decode() returns NULL with valid JSON?

Apparently, as I assumed earlier it was a formatting issue. I did not know that JSON would return NULL if the object includes non-UTF8 code and/or BOM codes.

I couldn't find any BOM codes but I suppose there was some non-UTF8 that was breaking it.

Long story short this works:

$dec =  json_decode( preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $response->body), true );         
 echo $dec['ticker'];

Well at least I now know a lot more about JSON which will come in handy some day ;)