Several things:
- The problem is not HTML entities, it is that the API always returns compressed data. Don't try to use
file_get_contents()
for that.
- Use cURL, but note that using cURL with HTTPS is not straightforward. See Using cURL in PHP to access HTTPS (SSL/TLS) protected sites for more information.
- Those
header
s do not set how data is fetched from the API, they control how your PHP page is returned to your browser.
- The given headers are somewhat invalid too, unless you mean for your PHP page to server JSON -- which the question code does not do.
- If you want the HTML source for the body, use
htmlentities()
Doc.
Putting it all together, your code would be something like this:
<?php
if (isset ($_REQUEST['id']) && !empty ($_REQUEST['id']) ) {
$id = $_REQUEST['id'];
$url = "https://api.stackexchange.com/2.2/questions/".$id."?site=stackoverflow&filter=!iCArD3YeTq5x1sbe4cmVxS";
$ch = curl_init ($url);
curl_setopt ($ch, CURLOPT_ENCODING, 'gzip');
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, false); // WARNING! This can be unsafe!
$cmprJson = curl_exec ($ch);
curl_close ($ch);
$json = $cmprJson;
//$json = gzdecode ($cmprJson); // Extra step needed on some server configs
$qstData = json_decode ($json);
$qstBody = $qstData->items[0]->body;
echo "<h1>The question body, page-ready, is:</h1>";
echo '<div style="margin: 0 2em 2em 2em; border: 1px dashed gray;">' . $qstBody . '</div>';
$bodyHtml = htmlentities ($qstBody);
echo "<h1>The question body HTML is:</h1>";
echo '<div style="margin: 0 2em 2em 2em; border: 1px dashed gray;">' . $bodyHtml . '</div>';
exit ();
}
else{
echo "Question id not available";
exit ();
}
?>