Shy
Shy

Reputation: 536

PHP variable has a value when echoed inside function, but is empty when echoed after being returned

In the following PHP snippet, there is a function named sendJsonByGet(). Inside this function's body, a variable named $response is created and populated. When I echo out this variable INSIDE the function, it gives the following output:

Response: Test Test Test

Then, as you can see in the snippet, I return the $response variable from the function, and the returned value is being assigned to a variable named $result, which is then echoed out. But this time, the output is:

Result:

The question is why?

PHP Script:

$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;

}

Upvotes: 0

Views: 39

Answers (1)

Adder
Adder

Reputation: 5868

It would appear that $response is not a valid JSON-Object-String, so the $result = json_decode($response) is null.

Upvotes: 0

Related Questions