PHP变量在函数内部回显时有一个值,但在返回后回显时为空

时间:2017-06-02 07:02:58

标签: php variables curl

在以下PHP代码段中,有一个名为sendJsonByGet()的函数。在此函数的主体内部,创建并填充名为$response的变量。当我在函数中回显这个变量时,它给出了以下输出:

Response: Test Test Test

然后,正如您在代码段中看到的那样,我从函数返回$response变量,并将返回的值分配给名为$result的变量,然后将其回显出来。但这一次,输出是:

Result:

问题是为什么?

PHP脚本:

$extractedDataArray = array(
    "DataFiles/datum.txt3" => "60340039" 
    );

$extractedDataJson = json_encode($extractedDataArray, JSON_FORCE_OBJECT);

$url = "http://AAA.BBB.CCC.DDD/TestTwo/index.php";

$result = json_decode(sendJsonByGet($url, $extractedDataJson));

echo "Result: $result";





function sendJsonByGet($url="http://AAA.BBB.CCC.DDD/TestTwo/index.php", $extractedDataJson) {
    $curlObject = curl_init($url);

    curl_setopt($curlObject, CURLOPT_CUSTOMREQUEST, "GET");
    curl_setopt($curlObject, CURLOPT_POSTFIELDS, $extractedDataJson);
    curl_setopt($curlObject, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt(   $curlObject, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Content-Length: ' . strlen($extractedDataJson) )   );

    $response= curl_exec($curlObject);

    echo "Response: $response";

    if (curl_error($curlObject)) {
        echo 'Error:' . curl_error($curlObject);
    }

    curl_close($curlObject);

    return $response;

}

1 个答案:

答案 0 :(得分:0)

$ response似乎不是有效的JSON-Object-String,因此$ result = json_decode($ response)为空。