我正在使用StackExchange获取项目的所有答案API。这样我就会点击网址 https://api.stackexchange.com/2.2/answers?page=10&pagesize=10&order=desc&sort=activity&site=stackoverflow在浏览器中点击原始json时显示,但问题是使用程序。
PHP
<?php
//step1
$cSession = curl_init();
//step2
curl_setopt($cSession,CURLOPT_URL,"https://api.stackexchange.com/2.2/answers?page=10&pagesize=10&order=desc&sort=activity&site=stackoverflow");
curl_setopt($cSession,CURLOPT_RETURNTRANSFER,true);
curl_setopt($cSession,CURLOPT_HEADER, false);
//step3
$result=curl_exec($cSession);
//step4
curl_close($cSession);
echo"<pre>";
var_dump($result);
echo "<br>";
echo"</pre>";
$jsonIterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator(json_decode($result, TRUE)),
RecursiveIteratorIterator::SELF_FIRST);
foreach ($jsonIterator as $key => $val) {
if(is_array($val)) {
echo "$key:";
echo"<br>";
} else {
echo "$key => $val";
echo"<br>";
}
}
?>
string(1194) "���mO�8ǿJ���m���=!��n�e�ǞN��84���K)��~NZ�4
�t���d����?�����O1��]�����;�=����:P�>�+�3eOb�U�f���1�O���T�G�Ȫt�E�ɴ�5ɣ�X�$�$Yj�խ,�T���dK�i��M��+k�Ǯ��#��r����HKٵJ_毀�.Jm�:�M�|m�!u���k���˼�$�r�,:u�����ϩ,�矗c��t�|�2�1u�@��ɨ���l6�G��Zu�_m�Cz����{4脄Oȃ����'����C�W�9��a��U�2Qv.�~C��淋ܩ����'�|a�.�/��ۼ���� �l
��u8".}��P�Y�e�he��
!a�`����<���>>������Aė!�[�;�E.�1��E ���rcv��7�#�4[�V��J����q�� �$�̇S���_W��d�t�'�W��'y�m����8��x�)���ӫ^q8&�#�F�6���X��+�6�����O2������{�g��I(�εR[Ld���7K�rߍzC8h#;�]��0�M�P1�~A��l�N�G^��2dBB#!��!$����3������I� )��
�-���n�םH�7H�
�g���y�"E���ۘ��2b��O�f�^}�u9tf�����!Ð�t�4}O
��MJ�[��iw�1n���uR��m=�6��<��Mw��]+�(��u��s��e��t>�~&�$7��FD�=��R�^�"
它像一些编码字符串一样显示结果,并给出解决方案。提前谢谢。
使用 '
gzdecode' 函数将从 GZIP JSON 解码
$ch = curl_init();
// Set the url
$url = "https://api.stackexchange.com/2.2/answers?page=10&pagesize=10&order=desc&sort=activity&site=stackoverflow";
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_HEADER, false);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);
// Will dump a beauty json :3
$result = gzdecode($result); // Here Decoding
print_r($result);
我收到如下
{"items":[{"owner":{"reputation":1642,"user_id":6373435,"user_type":"registered", ... . . .
试试这个它对我有用使用终端检查此 URL,它显示编码格式:gzip。因此,我们需要使用以下行对其进行编码。
curl_setopt($cSession, CURLOPT_ENCODING, 'gzip');
完整代码=>
$cSession = curl_init();
//step2
curl_setopt($cSession,CURLOPT_URL,"https://api.stackexchange.com/2.2/answers?page=10&pagesize=10&order=desc&sort=activity&site=stackoverflow");
curl_setopt($cSession, CURLOPT_ENCODING, 'gzip');//--------->>> Solution step
curl_setopt($cSession,CURLOPT_RETURNTRANSFER,true);
//curl_setopt($cSession,CURLOPT_HEADER, false);
//step3
$result=curl_exec($cSession);
//step4
curl_close($cSession);
echo"<pre>";
var_dump($result);
echo "<br>";
echo"</pre>";
谢谢 - 乌达亚桑卡。