如何使用cURL请求返回的数据?
问题描述:
I am passing an array for a php page to test but I can not get the data!
$data = array(
"user_id" => $login->id,
"discount_id" => $discount,
"product_id" => $product_id->id,
"date_payment" => $test->id
);
$fields_string = http_build_query($data);
$url = "http://localhost/dev/felipe/request-checkout.php";
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
$result = json_decode(curl_exec($ch));
curl_close($ch);
page.php:
extract($_POST);
$user_id = $_POST['user_id'];
$discount_id = $_POST['discount_id'];
$product_id = $_POST['product_id'];
$data_payment = $_POST['date_payment'];
echo $user_id . ' - ' . $discount_id . ' - ' . $product_id . ' - ' . $data_payment;
show null in $result in cURL. what I'm missing? how do I use the data and have a response which I did cURL?
我传递一个数组用于测试php页面,但我无法获取数据! p> \ n
$ data = array(
“user_id”=> $ login-> id,
“discount_id”=> $ discount,
“product_id”=> $ product_id - > id,
“date_payment”=> $ test-> id
);
$ fields_string = http_build_query($ data);
$ url =“http:// localhost / dev / felipe / request-checkout.php“;
$ ch = curl_init();
curl_setopt($ ch,CURLOPT_URL,$ url);
curl_setopt($ ch,CURLOPT_RETURNTRANSFER,TRUE);
curl_setopt($ ch ,CURLOPT_POST,1);
curl_setopt($ ch,CURLOPT_POSTFIELDS,$ fields_string);
$ result = json_decode(curl_exec($ ch));
curl_close($ ch);
code> pre >
page.php: p>
extract($ _ POST);
$ user_id = $ _POST ['user_id'];
$ discount_id = $ _POST ['discount_id'];
$ product_id = $ _POST ['product_id'];
$ data_payment = $ _POST ['date_payment'];
echo $ user_id。 ' - '。 $ discount_id。 ' - '。 $ product_id。 ' - '。 $ data_payment;
code> pre>
在cURL的$ result中显示null。 我错过了什么? 我如何使用数据并得到我做过cURL的响应? p>
div>
答
curl_exec($ch)
returns string in this format: "1 - 2 - 3 - 4"
.
When you try to run json_decode()
on this string, it returns null because this is not correct json format.
Instead of the echo $user_id . ' - ' . $discount_id . ' - ' . $product_id . ' - ' . $data_payment;
, you can endode an array/object to json string:
echo json_encode($_POST);