JSON API request in PHP not working Properly [duplicate] - php

This question already has answers here:
Decode gzipped web page retrieved via cURL in PHP
(2 answers)
Closed 2 years ago.
I'm struggling to retrieve data from an API using PHP.
My PHP code:
<?php
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://api.coronavirus.data.gov.uk/v1/data?filters=areaName=United%2520Kingdom;areaType=overview&structure={%22areaName%22:%22areaName%22,%22date%22:%22date%22,%22newCasesByPublishDate%22:%22newCasesByPublishDate%22,%22cumCasesByPublishDate%22:%22cumCasesByPublishDate%22}");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
curl_close($curl);
echo $output;
?>
Sadly this just outputs a random list of characters like this:
��9|_��M�\�E�JЀ���"�H*p�Kx���,:VK�`>���m��a˒��܆�V^��gt�d�e]���������������f�ӷ�7�?_�\=�^Z)�b�j��߽�����������{����������tu�������7����+/J���~���������>������o>|�y�v�����s��Et{���i��L;�+>�Pq�F7��ĵQ�u�q9s��e��*͈f hkh�T����Ӵn�ճ�4�Dk�4��E��q��J����XUi�4-r��j�9UZB���s)�J9��a&�z�� �$�Ͳ��n &��4���򺁖�� �a* ��UP�:Gz�4В:�Z�Pc�#KZsښJU'���mĔ3�#Kj�4KSU�#Kꜧ7�ڇ��ZR����ZUyݨ2I����`�֭�ӴQ�u-Y{JZX�i�%5*dwZ�;����4�Ű�FI�%A��3�������E�u��{#�e#TZm�uWidsVm� j�˱�`�V$��hrz�\���4�������Fǜ��%˩e�xQ��J-F�*�к�m��.��Q��y�m��2�4�+ݚJ��Ts�R�(!Ge�t���\��F�e���)� �kȤ�ZN4Tf��-���ςhَ&*���T�ɕ����ZA �R."��0�Y�#��Ԓ-��ֿ0�l#?թL�Uj��l,$�+md��t0�ȒLv�VM����f�$Abm�L#%)�hU�d�Sf�ݬ�vL�FǼ�k�VE�ܔ�%Y�/z�n��c�=UE&35��yd $3`�ʲ>jf��֬t�E��TvY��׬��(#"]�9%�u��4�'E���U�utQcК�}�T��*�浨0�J%T�Z� ��AkVr�kFj����iL ��0�+S��Y�H9�>u���S�O�S�I0��|�95-���g���Q +1d(HHԮ�Y�M=���IM�i8���T�PA��Ta�Ԇ��O���$*%�2����o�aU<��h��RR�2�.�#��cf�aT�8��JkF �!�O#y&����h$˔ #׎���yς�&è� ��|DO�;Z��$X3U��2yX�b��e��0��Ȩ�4���ZT<�iCK�D�t�i��D���m���Pa� k!����D3&^��������e֔i�2:��s�4�j��*��]z�3�G�tT�g<.�&7����V����^yY٦N$9�%���TF�a?ÿ�T׍��Q���e��6�w2�~L��m� �C�E��#wԏV^�7l5�uk�DPixZ\˅Ny��6�'���"�d�ͭ�5lj��}�J��88��Z�J���S�Ir5V��g�M��#[cx�5�}M�:��k{Suo� \7˔i�%��[�=BUe�U�p���%U��V]#[my�Z��.�V�*���z�4����݇�]�R^&�V�� o� �ɜ&^stS^(&���ʁv�W�p}l�\T)��]�#;�f *��S�U�YD�������\%��ft��*�(���ZO�z���#G�͐6L9*O�W�-[Qu�S������L��n��݊��B�sJ���M�Q����>�+ �F�)9�|��f7?�D�ó�%��Ҁ�������al6m�c#GUDŽ(�pyl䨖Z��cVS�q�O�t�PV��1I�j��%Ŭ��F���(�*�)�7�h%�*�U��\����VA�ڠ�~Fл��{k����Rh�b{���i�nv��M� |Ƙhf-TZ����{���&6�z��uW��UC��&�7kC�����D�n��T3�i�.�'��6��w1���,M��B{7e�r#M��81��м�Tc���]TiDR�G�Y K5���`���d��9�G�%����=�r(Й �W���Zx���q�#�^�P���b Oi�S1� &���sB#��sF#G�oB�M(e U�_�26��M(� %6��M(�99�Y�?T�mB)爲J�']N3*��W���7��93&S��}W)mJ݄�P��O1l=����U]�>]_� �[��V��(��V���n�#�h+e�����R�Jl+e�����R�Jl+e�����R���2����l�e+e([)C�J��������7W��ǫ����w������_��}u�������������ot�����������������˻����W��?<�?}��t�|ֿ~����_��_/��}����_��>~۩ώ?����S�=��<}w��������5-��_��_fk��������ç�����m��3W��ߦ���x����⶷nx
Putting the url directly into a browser works fine, giving a nice JSON, see see here.
I'm really scratching my head to know where to go from here to get this to parse properly in PHP.
Can anyone help, I'm completely out of my depth here.

Excellent....thank you soooo much !!!!!, you have just solved a problem I have been trying to sort out on-and-off for some time.

The retrieved data is encoded, to enable decoding, add this line.
curl_setopt($curl, CURLOPT_ENCODING, '');
This enables the decoding of the retrieved data, by using and empty string as parameter, it enables all encoding types.
With the line added, your code will look like this.
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://api.coronavirus.data.gov.uk/v1/data?filters=areaName=United%2520Kingdom;areaType=overview&structure={%22areaName%22:%22areaName%22,%22date%22:%22date%22,%22newCasesByPublishDate%22:%22newCasesByPublishDate%22,%22cumCasesByPublishDate%22:%22cumCasesByPublishDate%22}");
curl_setopt($curl, CURLOPT_ENCODING, ''); // <--- ADDED LINE!
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
curl_close($curl);
echo $output;

you need just encoding, this is working code:
<?php
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://api.coronavirus.data.gov.uk/v1/data?
filters=areaName=United%2520Kingdom;areaType=overview&structure{%22areaName%22:%22areaName%22,%22date%22:%22date%22,%22newCasesByPublishDate%22:%22newCasesByPublishDate%22,%22cumCasesByPublishDate%22:%22cumCasesByPublishDate%22}");
curl_setopt($curl, CURLOPT_ENCODING, '');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
curl_close($curl);
echo $output;
?>

Related

How to use PHP and curl to execute a POST call

I am trying to use curl with PHP to execute a POST call from PHP but always I get page error
this is my code
if($curl = curl_init()){
curl_setopt($curl, CURLOPT_URL, 'http://marcelotavarez.com/freeodds.aspx');
curl_setopt($curl, CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, "CallbackMethod=GetLines&Parm1=20170110&Parm2=2&Parm3=0&CallbackParmCount=3&__WW EVENTCALLBACK=CustomerCallback&__WWEVENTTARGET=Page&__VIEWSTATE=/wEPDwUKLTQwNjM5NzY1NmRkOa+UqFoVFF+BzUdMUBBH1ahGsWQ=&__VIEWSTATEGENERATOR=BB49A8FA&");
$out = curl_exec($curl);
echo "===\n $out \n====\n";
$out = str_replace("\"","",$out);
}
Using the inspector from Chrome I checked the header that I need to use to do the POST Call and these are:
CallbackMethod:GetLines
Parm1:"20170110"
Parm2:2
Parm3:0
CallbackParmCount:3
__WWEVENTCALLBACK:CustomerCallback
__WWEVENTTARGET:Page
__VIEWSTATE:/wEPDwUKLTQwNjM5NzY1NmRkOa+UqFoVFF+BzUdMUBBH1ahGsWQ=
__VIEWSTATEGENERATOR:BB49A8FA
Any time that I use this code just I get the error page
Any cluees or any help , pls
TIA
I need to ask you a question where is CallbackMethod=GetLines
GetLines function , I think must be in your code to be executed after response back

Decoding base64 string? please :(

<?php $OOO0O0O00=__FILE__;$O00O00O00=__LINE__;$OO00O0000=1132;eval((base64_decode('JE8wMDBPME8wMD1mb3BlbigkT09PME8wTzAwLCdyYicpO3doaWxlKC0tJE8wME8wME8wMClmZ2V0cygkTzAwME8wTzAwLDEwMjQpO2ZnZXRzKCRPMDAwTzBPMDAsNDA5Nik7JE9PMDBPMDBPMD0oYmFzZTY0X2RlY29kZShzdHJ0cihmcmVhZCgkTzAwME8wTzAwLDM3MiksJ0VudGVyeW91d2toUkhZS05XT1VUQWFCYkNjRGRGZkdnSWlKakxsTW1QcFFxU3NWdlh4WnowMTIzNDU2Nzg5Ky89JywnQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVphYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ejAxMjM0NTY3ODkrLycpKSk7ZXZhbCgkT08wME8wME8wKTs=')));return;?>
kr9NHenNHenNHe1lFMamb3klFoxiC2APk19gOLlHOa9gkZXJkZwVkr9NTznNHr8XHt4JkZwShokiF2A2Yy9LcBYvcoAPF3OZfuwPcmklCBWPkr8XHenNHr8XHtXLT08XHr8XHeEX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9UOAcyALaURtn0FmalhTShC3aZdy9zcbOvFuWPkoYPRtneaakHT1nAb1kyayaUTlOUWA5TOLaURuOZfBApKXpjfbkSb3Ylfo9XftILC2ISwrYaALxNAyOgarlYOA9aatXIYTEXhTShkuisduY0FMlVcz0IC3aZdy9lGoajhtOjDtL7tIPLGo1SF3OZDB5mwe0IkuisduY0FMlVczShkopzd25gFMaXduLINUnQF29Vb2OlC29LcUILGo1SF3OZDB5mRtn0FmalhTShtI==
I can't seem to decode this base64 string which is in the footer of a wordpress theme. I want to be able to add more to the footer.
Any help appreciated, thanks!
Ok, this is the decoded piece of code with readable variables (for educational purposes):
<?php
$the_current_file = __FILE__;
$the_line_number_of_this_line = __LINE__;
$fileResource = fopen($the_current_file, 'rb');
while (--$the_line_number_of_this_line) //For every line of code the code before this line
{
fgets($fileResource, 1024); //
}
fgets($fileResource, 4096);
$codeToEvaluate = (base64_decode(strtr(fread($fileResource, 372), 'EnteryouwkhRHYKNWOUTAaBbCcDdFfGgIiJjLlMmPpQqSsVvXxZz0123456789+/=', 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/')));
eval($codeToEvaluate);
return;
So basically, whereever this piece of code is included, it takes every line before it and replaces the characters EnteryouwkhRHYKNWOUTAaBbCcDdFfGgIiJjLlMmPpQqSsVvXxZz0123456789+/= with ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/. Then, it base64 decodes that and eval's it. I'd do a die($codeToEvaluate); before eval($codeToEvaluate) to find out what piece of code is executed.
But then, seriously. If the developers of this theme tried to obfuscate something from you, either it's malicious or you're trying to crack past some licensing because you don't want their attribution in the footer. Credit them or pay them.
So bottom line: Buy the goddamn theme or find another.
EDIT
This seems to be the code, thats being executed:
$purchasecode = PURCHASE_CODE;
$target_url = "http://www.jobzeek.com/api/search/?jobzeek=$jobzeek&indeed=$indeed&careerjet=$careerjet&purchasecode=$purchasecode&keyword=$q&location=$l&co=$co&sort=$sort&radius=$radius&st=$st&jtype=$jt&start=$start&old=$fromage";
//echo $target_url;
$userAgent = 'Googlebot/2.1 (http://www.googlebot.com/bot.html)';
// make the cURL request to $target_url
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
curl_setopt($ch, CURLOPT_URL, $target_url);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 500);
$xmlstring = curl_exec($ch);
$xmlstring = $xmlstring;
$json_reply = json_decode($xmlstring, true);
Nice try, your base64 look like this:
$O000O0O00=fopen($OOO0O0O00,'rb');
while(--$O00O00O00)
fgets($O000O0O00,1024);
fgets($O000O0O00,4096);
$OO00O00O0(base64_decode(strtr(fread($O000O0O00,372),'EnteryouwkhRHYKNWOUTAaBbCcDdFfGgIiJjLlMmPpQqSsVvXxZz0123456789+/=','ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/')));
eval($OO00O00O0);%
Ahm.... yeah, i'm not gonna execute eval on that.

php curl_setopt() returns json data with "1" on end

so I have a curl_setopt that is pulling a json file just fine with php. It does this with one exception, at the end of the json data there is a one (1) on the end after the last '}'. This "1" is not apparent in the url call by itself without using curl though. So it seems my curl_setopt is not configured properly. Can someone help with this?
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $domain.$args);
curl_setopt($ch, CURLOPT_HEADER, false);
$json = curl_exec($ch);
curl_close($ch);
the $domain.$args is working fine as I can echo out this variable setup and produce the json manually via browser without the 1.
appreciate the help
/** edit after suggestions **/
I tried the suggestion below of adding:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
this just ended up changing the entire json output, not just adding a "1" on the end of the response:
"{\"data\":[{\"Name\":\"A3\",\"SeoName\":\"a3\"},{\"Name\":\"A4\",\"SeoName\":\"a4\"},{\"Name\":\"A5\",\"SeoName\":\"a5\"},{\"Name\":\"A6\",\"SeoName\":\"a6\"},{\"Name\":\"A7\",\"SeoName\":\"a7\"},{\"Name\":\"A8\",\"SeoName\":\"a8\"},{\"Name\":\"allroad\",\"SeoName\":\"allroad\"},{\"Name\":\"Q5\",\"SeoName\":\"q5\"},{\"Name\":\"Q5 hybrid\",\"SeoName\":\"q5-hybrid\"},{\"Name\":\"Q7\",\"SeoName\":\"q7\"},{\"Name\":\"R8\",\"SeoName\":\"r8\"},{\"Name\":\"RS 5\",\"SeoName\":\"rs-5\"},{\"Name\":\"RS 7\",\"SeoName\":\"rs-7\"},{\"Name\":\"S4\",\"SeoName\":\"s4\"},{\"Name\":\"S5\",\"SeoName\":\"s5\"},{\"Name\":\"S6\",\"SeoName\":\"s6\"},{\"Name\":\"S7\",\"SeoName\":\"s7\"},{\"Name\":\"S8\",\"SeoName\":\"s8\"},{\"Name\":\"SQ5\",\"SeoName\":\"sq5\"},{\"Name\":\"TT\",\"SeoName\":\"tt\"},{\"Name\":\"TTS\",\"SeoName\":\"tts\"}]}"
Use this:
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
Fix but not ideal is to substr() it to strip out the 1.
substr($result, 0, strlen($result) - 1);

How to pass data containing special characters through curl

I cannot able to post data its contain the special characters through curl ,Any solution ?
first code is my curl function ,second code is my data need to pass
$communication_data_string = 'token='.json_encode(array(
"activityTypeId"=>12,
"activityId"=>5,
"userID"=> 10,
"partyID"=>20,
"message_area_name"=>("this is my test data with special cheractors&&!###$%$%%*)++")
)
);
echo(datPostingCURL($url, $communication_data_string));
?>
this seems to not returning anything if the messageData contains the special character's
Try urlencode
or
How about using the entity codes...
# = %40
& = %26
change the line
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
to
curl_setopt($ch, CURLOPT_POSTFIELDS, urlencode($data_string));
the receive it in following way as you are not using any specific post variable
$data = urldecode(file_get_contents('php://input'));
Check the following code. I tested it in my local system. In my www director I created a folder named "test" for keeping the code. Then I created 2 files in that "test" folder. One file for sending the request and one for processing the request.
1. curl.php
<?php
function datPostingCURL($url, $data_string)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
return $result;
}
$url = "http://localhost/test/curl_post.php";
$communication_data_string = 'token='.json_encode(array(
"activityTypeId"=>12,
"activityId"=>5,
"userID"=> 10,
"partyID"=>20,
"message_area_name"=>base64_encode("hai ..this is my test data .!###$%$%%*)++")
)
);
echo(datPostingCURL($url, $communication_data_string));
?>
2. curl_post.php
<?php
print_r(json_decode($_POST['token']));
$details = json_decode($_POST['token']); var_dump($details);
echo base64_decode($details->message_area_name);
?>
Note : While using special characters you should encode that string. I tried to convert it with htmlspecialchars(). But it didn't worked. So I used base64 encoding method here.

Help w/ Retrieving XML via cURL

I've run into trouble with the following php code:
<?php
$url = "http://api.ean.com/ean-services/rs/hotel/v3/list? minorRev=1&cid=55505&apiKey=58x5kuujub8xbb5tzv3a2a8q&locale=en_US&currencyCode=USD&xml= <HotelListRequest><destinationString>Seattle</destinationString> <arrivalDate>08/01/2011</arrivalDate><departureDate>08/03/2011</departureDate><RoomGroup> <Room><numberOfAdults>2</numberOfAdults></Room></RoomGroup> <numberOfResults>1</numberOfResults></HotelListRequest>";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
$contents = curl_exec ($ch);
echo $contents;
curl_close($ch);
?>
The problem is that $contents contains markup that's not XML at all, so I can't parse it. It's confusing b/c entering the URL in my browser's address bar will display the XML document, but I can't seem to get a valid XML doc w/ this code.
Here is a snippet of the string that gets returned:
{"HotelListResponse":{"customerSessionId":"0ABAA83D-4428-4913-0382-28FBB1901EFC","numberOfRoomsRequested":1,"moreResultsAvailable":true,"cacheKey":"-32344284:1303828fbb1:-1ef9","cacheLocation":"10.186.168.61:7305","HotelList":{"#size":"1","HotelSummary":{"#order":"0"
Could someone explain to me where I'm going wrong?
Thx.
Instead of trying to get XML, which may not be provided, you could always work with what you have, which appears to be JSON.
$response = json_decode( $contents, true );
This will give you an associative array of your data, which can be much easier to work with.
Try to remove spaces: "/v3/list? minorRev=1" -> "/v3/list?minorRev=1"
Make your URL correct, like
$url = 'http://api.ean.com/ean-services/rs/hotel/v3/list?type=xml&minorRev=1&cid=55505&apiKey=58x5kuujub8xbb5tzv3a2a8q&locale=en_US&currencyCode=USD&xml=%3CHotelListRequest%3E%3CdestinationString%3ESeattle%3C/destinationString%3E%3CarrivalDate%3E08/01/2011%3C/arrivalDate%3E%3CdepartureDate%3E08/03/2011%3C/departureDate%3E%3CRoomGroup%3E%3CRoom%3E%3CnumberOfAdults%3E2%3C/numberOfAdults%3E%3C/Room%3E%3C/RoomGroup%3E%20%3CnumberOfResults%3E1%3C/numberOfResults%3E%3C/HotelListRequest%3E';
Add option to accept xml only -- in browser we have such header -- in curl -- no:
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/xml'));
PROFIT!!!

Categories