1

I am trying to get post details using JSON in wordpress. In my plugin following is the json_decode part. But it returns null.

$post_count = intval($instance['post_count']);
$eng_posts= @json_decode(file_get_contents("http://athavaneng.com/?page_id=206861&posts_per_page=".$post_count), true);
switch (json_last_error()) {
    case JSON_ERROR_NONE:
        echo ' - No errors';
    break;
    case JSON_ERROR_DEPTH:
        echo ' - Maximum stack depth exceeded';
    break;
    case JSON_ERROR_STATE_MISMATCH:
        echo ' - Underflow or the modes mismatch';
    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_UTF8:
        echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
    break;
    default:
        echo ' - Unknown error';
    break;
}

In the above code I get a JSON_ERROR_SYNTAX error. But actually when I test the returning JSON data of http://athavaneng.com/?page_id=206861 URL on the http://jsonlint.com. It says that "Valid JSON".

Why is that? What is the problem here?

3
  • The problem is that you didn't pull out your packet sniffer to figure out what PHP is requesting and what the response actually is. Commented Jun 2, 2015 at 8:16
  • checking your URL with jsonlint (not pasting the json directly) gives JSON.parse: unexpected character at line 1 column 1 of the JSON data Commented Jun 2, 2015 at 8:22
  • Please tell me how to solve that issue?? Commented Jun 2, 2015 at 8:44

1 Answer 1

2

The responding server is sending 3 strange chars before it starts the json output. By doing this:

$var = file_get_contents("http://athavaneng.com/?page_id=206861&posts_per_page=1");

for($i=0; $i<10; $i++) {    
    echo $var[$i] . " : " . ord($var[$i]) . "<br />";    
}

you will get something like this:

ï : 239
» : 187
¿ : 191
{ : 123
" : 34
1 : 49
" : 34
: : 58
{ : 123
" : 34

the first three chars (239,187 and 191) should not been printed by the server. As a workaround you should be able to parse it after stripping the first three chars.

I am able to parse your json with the following code, which beginns reading at character 3:

$var = file_get_contents("http://athavaneng.com/?page_id=206861&posts_per_page=1", false, NULL, 3);
var_export(json_decode($var));
Sign up to request clarification or add additional context in comments.

1 Comment

Hi steven. You are best. Thank you for the answer and it is working excellent. I am sad that not able to vote up because of I havent enough reputations. Thank you so much Steven.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.