0

我目前有一个返回 JSON 的 API 脚本。它一直有效,直到我尝试curl php POST在它之前添加一个脚本。curl 脚本自己运行,它也在 API 脚本中运行。但是 JSON 代码不会被返回。

下面的这种方法有什么根本错误吗?

提前致谢。

编辑:该curl脚本可以 100% 自行运行。所述脚本也在下面工作,只是JSON没有返回。

$name   = "foo";
$age    = "bar";

//set POST variables
$url = 'https://www.example.com';

$fields = array(
            'name' => urlencode($name),
            'age' => urlencode($age)
        );

//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

//execute post
$result = curl_exec($ch);

//close connection
curl_close($ch);    
return json_encode(
    array(
        "status" => 1,
        "message" => "Success!",
        "request" => 10
    )
);
4

1 回答 1

2

您需要执行以下使用,如果不是echo,也使用CURLOPT_RETURNTRANSFER输出将直接传输到页面而不是$result

$name = "foo";
$age = "bar";
$url = 'http://.../a.php';
$fields = array('name' => urlencode($name),'age' => urlencode($age));
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$result = curl_exec($ch);
curl_close($ch);

header('Content-type: application/json'); 
echo json_encode(array("status" => 1,"message" => "Success!","request" => 10));
于 2012-10-10T15:49:22.127 回答