Categories
PHP

How to convert JSON string to array

If you pass the JSON in your post to json_decode, it will fail. Valid JSON strings have quoted keys:

json_decode('{foo:"bar"}');         // this fails
json_decode('{"foo":"bar"}', true); // returns array("foo" => "bar")
json_decode('{"foo":"bar"}');       // returns an object, not an array.

Ref: https://stackoverflow.com/questions/7511821/how-to-convert-json-string-to-array

Categories
PHP

PHP cURL retrieve response headers AND body in a single request

$url = "https://www.googleapis.com";
$ch = curl_init();
$headers = [];
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$body = curl_exec($ch);

// this function is called by curl for each header received
curl_setopt(
    $ch,
    CURLOPT_HEADERFUNCTION,
    function ($curl, $header) use (&$headers) {
        $len = strlen($header);
        $header = explode(':', $header, 2);
        if (count($header) < 2) { // ignore invalid headers
            return $len;
        }

        $headers[strtolower(trim($header[0]))][] = trim($header[1]);

        return $len;
    }
);

$data = curl_exec($ch);
print_r($headers);
print_r($body);

Ref: https://stackoverflow.com/questions/9183178/can-php-curl-retrieve-response-headers-and-body-in-a-single-request