1

So, I'm porting from Java to Php a simple server supposed to serve strings in json format. I'm no Php programmer, but I'm learning. The problem is that don't really understand how to send back to my client a raw json string (I swear I googled it for a couple of hours before with no luck).

my client Php script initializes a curl session and sends a request in Json format, kind of easy:

    $command = array("command" => "ping");
    $content = json_encode($command);

    //Initialize curl
    $curl = curl_init("http://localhost/test/server.php");
    curl_setopt($curl, CURLOPT_HEADER, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type: application/json"));
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $content);

    echo "Client: Tried to initialize curl<br>";
    $response = curl_exec($curl);
    echo "Client: reponse: " . $response . "<br>";
    $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    echo "Client status: " . $status . "<br>";

    if ($status != 200) {
        die("Client: Error: call to URL $url failed with status $status, response: $response, curl_error: " . curl_error($curl) . ", curl_errno: " . curl_errno($curl) . "<br>");
    }

    curl_close($curl);
    echo "Response: <br>";
    $json_response = json_decode($response, true);

Now, I'm stuck in the server side, I can get and decode the Json request (in this case a command called "ping"), I want to send back a raw Json string like {"command":"pong"}

    $data = json_decode(file_get_contents("php://input"), true);
    $req = $data['command'];
    switch ($req) {
        case "ping":
            ping();
            break;
        default:
            echo "SERVER: unrecognized command: " . $data["command"] . "<br>";
    }

    function ping(){
        $command = array('command' => 'pong');
        print_r(json_encode($command)); // WRONG! should send back a raw json string
    }

How do I send back a raw json string? Another curl operation? And at which url?

Miguel El Merendero
  • 2,054
  • 1
  • 17
  • 17

1 Answers1

1

You should use echo instead of print_r, and set the response header to "application/json" :

 function ping(){
        $command = array('command' => 'pong');
        header('Content-Type: application/json');
        echo json_encode($command);
    }

See HTTP Content-Type Header and JSON

Community
  • 1
  • 1
Jb Drucker
  • 972
  • 8
  • 14