How do I read an XSLX file with Curl in PHP?

18 hours ago 1
ARTICLE AD BOX

Your code is fine for binary files. CURLOPT_RETURNTRANSFER does not care whether the response is text, XLSX, or ZIP.

The problem is probably that the server is rejecting the request or redirecting it, and you are not checking the cURL error/status code.

Try this:

$c = curl_init($sourceURL); curl_setopt_array($c, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => true, CURLOPT_FAILONERROR => false, CURLOPT_USERAGENT => 'Mozilla/5.0', ]); $contents = curl_exec($c); if ($contents === false) { die('cURL error: ' . curl_error($c)); } $httpCode = curl_getinfo($c, CURLINFO_HTTP_CODE); $contentType = curl_getinfo($c, CURLINFO_CONTENT_TYPE); curl_close($c); echo "HTTP code: $httpCode\n"; echo "Content type: $contentType\n"; echo "File returned " . strlen($contents) . " bytes\n"; if ($contents === '' || $httpCode >= 400) { die("Download failed\n"); } file_put_contents($targetFilename, $contents);

The important parts are:

CURLOPT_FOLLOWLOCATION => true

because downloads are often redirected, and:

curl_error($c) curl_getinfo($c, CURLINFO_HTTP_CODE)

because curl_exec() can return an empty string without your code showing why.

Also, don’t use this check:

if (!file_put_contents(...))

Use this instead:

if (file_put_contents($targetFilename, $contents) === false)

because file_put_contents() can return 0, and 0 is treated as false in PHP.

Read Entire Article