Error getting json with php

I have a problem getting json information using PHP.

I created a simple php page that returns json:

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

And on another page, I'm trying to get this 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 get "JSON_ERROR_SYNTAX" because after the function "file_get_contents" I have an unknown character at the beginning of the line.

If I copy / paste it into Notepad ++, I have not seen:

 {"title":"Simple title"} 

but i see:

 ?{"title":"Simple title"} 

Can someone help me?

+3
source share
4 answers

Make sure that both of your scripts have the same encoding - and if UTF makes sure that they do not have a byte mark (BOM) at the very beginning of the file.

+3
source

What about

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

?

Also, there seems to be a problem with the encoding inside PHP, which echo your JSON. Try setting the correct (as in: content-type ) headers and make sure that both files are encoded in UTF-8 format.


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

+1
source

I'm sure your page that has json_encode has roaming ? . Look where there is no > in terms of ?> Etc.

+1
source

Check out your PHP for the wandering "?".

0
source

Source: https://habr.com/ru/post/903866/


All Articles