在php中创建一个json回复


Create a json reply in php

因此,我正在将一个简单的服务器从Java移植到Php,该服务器应该以json格式提供字符串。我不是博士程序员,但我在学习。问题是,我真的不知道如何向我的客户发送一个原始的json字符串(我发誓我之前在谷歌上搜索了几个小时,但没有运气)。

我的客户端Php脚本初始化一个curl会话,并以Json格式发送一个请求,有点简单:

    $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);

现在,我被困在服务器端,我可以获得并解码Json请求(在这种情况下是一个名为"ping"的命令),我想发回一个原始Json字符串,如{"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
    }

如何发回原始json字符串?又一次卷曲手术?在哪个网址?

您应该使用echo而不是print_r,并将响应标头设置为"application/json":

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

请参阅HTTP内容类型标头和JSON