CURL PHP POST会干扰JSON

时间:2012-10-10 15:16:18

标签: php json http post curl

我目前有一个返回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
    )
);

1 个答案:

答案 0 :(得分: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));