Search code examples
phpjsonhttpresponsemp4php-curl

Extract video data from api response using PHP


I am using the following cURL in PHP for an API request to obtain a video file as recommended by the api provider. That is the extent of their documentation.

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, $payload_json);

$response = curl_exec($curl); 

When I save the response to a file and then look at it in a text editor, it looks like the following:

HTTP/1.1 200 OK
Date: Fri, 20 Dec 2024 21:23:34 GMT
Content-Type: application/json; charset=UTF-8
Content-Length: 3292160
Connection: keep-alive
Access-Control-Allow-Origin: *
x-request-id: a1d0850f892cb9b4fc357a3532e81b91
Server: cloudflare
CF-RAY: 8f52b1b34f7f8ff9-BOS
alt-svc: h3=":443"; ma=86400

{"video":"AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAAIZnJlZQAlpQhtZGF0AAACrwYF//+r3EXpvebZSLeWLNgg2SPu73gyNjQgLSBjb3JlID - 2 megs more of characters that are probably the video"}

ChatGPT says to extract the video with a string operation eg searching for \r\n\r\n and deleting everything up to that but I feel like there must be a cleaner way.

How can i grab the video alone and put it in a variable.

Thanks in advance for any suggestions


Solution

  • Tell curl that you don't want the response headers included in the response. You shouldn't need to do this, because not including the headers is the default behavior, but you're clearly getting them.

    curl_setopt($curl, CURLOPT_HEADER, false);
    

    Then your response will be just:

    {"video":"..."}
    

    Which you can then process with json_decode():

    $data = json_decode($response, true);
    $video = $data['video'];
    

    You probably also want to check the response code for a success, which would make your script something like:

    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $payload_json);
    curl_setopt($curl, CURLOPT_HEADER, false);
    $info = curl_getinfo($curl);
    $response = curl_exec($curl);
    curl_close($curl);
    if ($info['http_code'] != 200) {
        throw new Exception('Unexpected HTTP response code');
    }
    $data = json_decode($response, true);
    if (empty($data)) {
        throw new Exception('Erroneous or empty JSON packet.');
    }