3

I've some problem retrieving json information with a PHP.

I've created a simple php page that returns a json:

$data = array(
    'title' => 'Simple title'
);
print json_encode($data);

And in another page I try to get that array as an object:

$content = file_get_contents($url);
$json_output = json_decode($content, true); 

switch(json_last_error())
{
    case JSON_ERROR_DEPTH:
        echo ' - Maximum stack depth exceeded';
        break;
    case JSON_ERROR_CTRL_CHAR:
        echo ' - Unexpected control character found';
        break;
    case JSON_ERROR_SYNTAX:
        echo ' - Syntax error, malformed JSON';
        break;
    case JSON_ERROR_NONE:
        echo ' - No errors';
        break;
}

The problem is that there is an error with this approach: I receive a "JSON_ERROR_SYNTAX" because after "file_get_contents" function I have an unknown character at the beginning of the string.

If I copy/paste it on Notepad++ I didn't see:

{"title":"Simple title"}

but I see:

?{"title":"Simple title"}

Could someone help me?

2
  • A little update: if I use the php function "utf8_encode" on the returned string, there is this "" at the beginning of the string... I don't know why ... Commented Oct 3, 2011 at 14:01
  • That's UTF-8 BOM (en.wikipedia.org/wiki/Byte_order_mark), you should delete it ;) Commented Oct 3, 2011 at 14:06

4 Answers 4

2

Make sure both your scripts have same encoding - and if it's UTF make sure they are without Byte Order Mark (BOM) at very begin of file.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I converted my php file with Notepad++ and all works! First time I hear about it.
1

What about

$content = trim(file_get_contents($url));

?

Also, it sounds as if there was a problem with the encoding within the PHP that echos your JSON. Try setting proper (as in: content-type) headers and make sure that both files are UTF-8 encoded.


Also: What happens if you open $url in your browser? Do you see an "?"

2 Comments

Thank for your answer, but the problem still exists... 1) I tried with the "trim" function - no result 2) I added "header('Content-Type:text/html; charset=UTF-8');" - no result 3) I check my files: they are both UTF-8
I've also open my url in my browser, but there isn't any "?".
1

I am pretty sure your page that does the json_encode has a stray ?. Look in there for a missing > in terms of ?> and such.

1 Comment

I checked it, but I don't have the terminator like "?>": every php file begin with "<?php" and doesn't have any ending string to avoid this type of errors.
0

Look through your PHP for a stray "?".

1 Comment

There isn't any "?" in my php code, it was the first thing I tried :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.