Mert Saygı
Mert Saygı

Reputation: 139

PHP doesn't parse my json output

Hello i want to read a json data in php. I created my services but there is a problem here my expected string doesn't shown in my web page. Then i create test service a bit easy than before service. Nothing changed.

Expected result is: "Session is Not Null"

Founded result is: "{"

My Services:

    $service = $_GET['service'];

switch($service)
{
case "create_ktt":  saveInfo(); break;
case "create_user": createUser();   break;
case "login_user":  loginUser();    break;
case "logout_user": logoffUser();   break;
case "get_session": getSession();   break;
case "get_report":  getReport();    break;
case "test_json":
    header('Content-type: application/json');
    echo json_encode('{"session_code":"1","message":"Session is Not Null"}');
    break;
default:
    sendError(2);
    break;
}

My Read Area:

<?php

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_URL, 'http://e-trafik.esy.es/external_services.php?service=test_json');
curl_setopt($curl, CURLOPT_TIMEOUT, 15);
curl_setopt($curl, CURLOPT_VERBOSE, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($curl, CURLOPT_FAILONERROR, 0);
$result_json = curl_exec($curl);

$decodeislemi = json_decode($result_json);

$mesaj = $decodeislemi[message];

echo $mesaj;

?>

PS: I changed my $mesaj = $decodeislemi[message]; line to $mesaj = $decodeislemi->message; nothing changed.

Upvotes: 0

Views: 77

Answers (2)

STW
STW

Reputation: 46366

Testing your service's URL in a JSON validator shows that your JSON is invalid.

http://jsonlint.com/

The issues is that you're double-encoding your JSON. As AbraCadaver suggests you should be passing an array of key:values to json_encode(), or returning your string (without using json_encode), but not both.

Here's a comparison:

Your service is currently returning this:

"{\"session_code\":\"1\",\"message\":\"Session is Not Null\"}"

Your service should be returning this:

{"session_code":"1","message":"Session is Not Null"}

To resolve it you need to replace this:

echo json_encode('{"session_code":"1","message":"Session is Not Null"}');

with either of these

echo json_encode(["session_code"=>"1","message"=>"Session is Not Null"]);
echo '{"session_code":"1","message":"Session is Not Null"}';

Upvotes: 0

AbraCadaver
AbraCadaver

Reputation: 78984

Looks like you are trying to construct your own JSON string and then encode it? Try using an array:

echo json_encode(["session_code"=>"1","message"=>"Session is Not Null"]);

Or I suppose you could build it yourself (not recommended) and echo it:

echo '{"session_code":"1","message":"Session is Not Null"}';

Upvotes: 1

Related Questions