简体   繁体   中英

PHP Curl not storing json_encoded echoed data

Does anyone no if it is possible to store echoed results from a Curl script.

Example of script been submitted to:

\\some code to generate images using imagick and the post variables

$array = array(1,2,3,4,5,6,7,8,9);
$result = json_encode($array);
echo $result;

Example of Curl:

$id = 1;
$champ = array("product" => "1","id"=> $id,"occasion"=> $o,"field1" => "1991","field2" => "test","field3" =>"test1","field4" => "test2","field5" =>"test3","field6" =>"test4","field7" =>"test5","field8" =>"test6","test7");
foreach($champ as $key => $data){
    $field_string .= $key."=".$data."&";
}
rtrim($field_string, "&");

$url = "http://www.test.com/website/script.php";
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST, count($champ));
curl_setopt($ch,CURLOPT_POSTFIELDS, $field_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, FALSE);
$result = curl_exec($ch);
$array = json_decode($result);
curl_close($ch);
var_dump($array);

If i var_dump($result) i get a bool(true) so i know that the script has executed correctly and the output shows on screen however i don't seem to be able to store the information into a variable to process.

Thank you in advance

As curl_exec documentation says:

curl_exec() returns TRUE on success or FALSE on failure.
However, if the CURLOPT_RETURNTRANSFER option is set,
it will return the result on success, FALSE on failure.

In your case you turn CURLOPT_RETURNTRANSFER off. Turn it on by

curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

and check the $result again.

Note: building a request using foreach loop and rtrim() you may damage it if your data contains & character.

Just use http_build_query() with your $champ :

curl_setopt($ch,CURLOPT_POSTFIELDS, http_build_query($champ));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM