0

Good evening everyone

I'm kinda speechless right now. I'm working with PHP for quite a long time, but I can't manage to get a simple JSON string decoded.

So what I have so far:

A simple script representating the issue:

<?php
  $twasiapiraw = file_get_contents("https://twasi.net/api/spendencoins/get/41847584?API_KEY=TWASI_PUBLIC_KEY");
  $twasiapifake = '{"code":200,"message":"OK","coins":[{"twitch_id":"41847584","coins":0,"twitch_name":"mekalix"}]}';
  var_dump(trim($twasiapiraw));
  echo "<br>";
  var_dump(trim($twasiapifake));
?>

So the outputs does match perfectly, this screenshot makes this clear: Comparison What's very strange is that they appear to have a different length (One 99, the other 96). I have also tried it without trim, but I tought that there could be some line breaks at the end.

The JSON is valid, but when I try to decode it, this will result in a PHP Json Error 4 - Syntax Error. But I'm sure that this may solve itself when both strings have the same length. How can I get both strings to match?

I appreciate any help or tipps.

Larce
  • 841
  • 8
  • 17
  • Judging by your `
    `, I'm going to assume you're trying to view this in a browser. Have you viewed the raw output (View Source)? Trim only strips whitespace from the beginning and end, not inside the string. There could be line breaks or other characters in the middle of the JSON string.
    – Devon Bessemer May 09 '17 at 20:37
  • Maybe there are control chars, which are not visible. Look at this http://stackoverflow.com/questions/1497885/remove-control-characters-from-php-string – Fran Cerezo May 09 '17 at 20:39
  • thank you for those ideas! Devon I viewed the raw source output and it was exactly the same to, and @Fran Cerezo, I will check that out tomorrow, thanks for your hint! – Larce May 09 '17 at 20:42

1 Answers1

2

There's a Byte Order Mark at the beginning of the string you're getting from the API.

You can remove it.

if (substr($twasiapiraw, 0, 3) == "\xef\xbb\xbf") {
    $twasiapiraw = substr($twasiapiraw, 3);
}

It's there to indicate that the string is UTF-8 encoded, but json_decode only works with UTF-8 encoded strings anyway.

Don't Panic
  • 41,125
  • 10
  • 61
  • 80