当通过变量传递json数据时,CURL没有返回正确的响应

时间:2018-10-30 11:21:07

标签: php-curl jdoodle

$data是包含json字符串{"clientId":"MyClientID","clientSecret":"MyClientSecret","script":"<?php\n echo \"Welcome to GLB Coding Club\";\n?>\n","stdin":"","language":"php","versionIndex":"2"}的变量。

如下面第一行所示。我已使用json_encode()

将数组编码为json
$data = json_encode(array("clientId"=>"MyClientID","clientSecret"=>"MyClientSecret","script"=> $this->input->post("script",true),"stdin"=>$this->input->post("stdin",true),"language"=>$this->input->post("language",true),"versionIndex"=>$this->input->post("versionIndex",true)));

        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => "https://api.jdoodle.com/v1/execute",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => $data,
            CURLOPT_HTTPHEADER => array("cache-control: no-cache","content-type: application/json"),
            CURLOPT_SSL_VERIFYPEER => false
        ));

        $response = curl_exec($curl);
        $err = curl_error($curl);
        curl_close($curl);

        if ($err) {
            echo "cURL Error #:" . $err;
        } 
        else {
            echo $response;
        }

jdoodle没有返回正确的$response,而是返回了要执行的语句。但是,如果我在$data处将{"clientId":"MyClientID","clientSecret":"MyClientSecret","script":"<?php\n echo \"Welcome to GLB Coding Club\";\n?>\n","stdin":"","language":"php","versionIndex":"2"}替换为实际的json字符串CURLOPT_POSTFIELDS => $data,则jdoodle返回正确的$response

2 个答案:

答案 0 :(得分:0)

然后,简单地

json_encode(array("clientId"=>"MyClientID","clientSecret"=>"MyClientSecret","script"=> $this->input->post("script",true),"stdin"=>$this->input->post("stdin",true),"language"=>$this->input->post("language",true),"versionIndex"=>$this->input->post("versionIndex",true)))

没有产生您期望的$data字符串,并且给出了正确的响应:

'{"clientId":"MyClientID","clientSecret":"MyClientSecret","script":"<?php\n echo \"Welcome to GLB Coding Club\";\n?>\n","stdin":"","language":"php","versionIndex":"2"}'

只是

echo $data;
exit(0);

在第一行之后,检查形成$data字符串时出了什么问题

答案 1 :(得分:0)

我只是将$this->input->post("script",true)修改为html_entity_decode($this->input->post("script",true))