PHP CURL调用glitch.me域名API返回防护页面HTML而非JSON的解决方法咨询
The problem you're facing is almost certainly due to the API's protection mechanism checking for standard HTTP headers that browsers and Postman send automatically, but which PHP cURL doesn't include by default. Specifically, headers like User-Agent (to identify the client) and Accept (to specify the desired response format) are likely missing from your request.
Here's how to modify your cURL code to include these headers, which should mimic the requests made by Postman/browser and get you the JSON response:
$curl = curl_init(); $url = 'https://thesimpsonsquoteapi.glitch.me/quotes?count=1'; curl_setopt_array($curl, array( CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_FOLLOWLOCATION => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => 'GET', // Add these headers to mimic a browser/Postman request CURLOPT_HTTPHEADER => array( 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36', 'Accept: application/json' ), )); $response = curl_exec($curl); curl_close($curl); // Verify the response is JSON var_dump(json_decode($response));
Why this works:
- User-Agent: Most anti-scraping mechanisms block requests with generic or empty User-Agent strings. By setting a valid browser-like User-Agent, you signal to the server that your request is coming from a legitimate client.
- Accept: This header tells the server you explicitly want a JSON response, which helps it bypass any default HTML fallback pages.
If this still doesn't work, you can try copying the exact headers from your working Postman request:
- In Postman, go to the "Headers" tab of your successful request.
- Copy all the headers listed there (excluding any Postman-specific ones like
Postman-Token). - Add them to the
CURLOPT_HTTPHEADERarray in your PHP code.
This should ensure your cURL request matches the one that works in Postman exactly.
内容的提问来源于stack exchange,提问作者Potralso

