use php to parse json data posted from another php file - php

my web hosting has blocked the outward traffic so i am using a free web hosting to read data and post it to my server but the problem is that my php file receives data in the $_REQUEST variable but is not able to parse it.
post.php
function postCon($pCon){
//echo $pCon;
$ch = curl_init('http://localhost/rss/recv.php');
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, "data=$pCon");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$d=curl_exec ($ch);
echo $d."<br />";
curl_close ($ch);
}
recv.php
<?php
if(!json_decode($_REQUEST['data']))
echo "json error";
echo "<pre>";
print_r($data);
echo "</pre>";
?>
every time it gives json error.
but echo $_REQUEST['data'] gives the correct json data.
plz help.

Should not this ?
$posts = array('data'=>$pCon);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $posts);
even the example in doc show that
from doc
The full data to post in a HTTP "POST" operation. To post a file, prepend a filename with # and use the full path. This can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value. If value is an array, the Content-Type header will be set to multipart/form-data. As of PHP 5.2.0, files thats passed to this option with the # prefix must be in array form to work.
your existing way should work too,
is it possible that $pCon contains some urlencoded values such as =, ? ?

$posts = array('data'=>$pCon);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $posts);
this worked.
(the person who answered this question deleted the post so i couldnt catch his name, so thankx)
edit:
there still was a small error every quote (") was changed to (\") i had a very hard time correcting this so now i am not sending data in json directly but first base64 encode it and when the page receives it , it base64 decodes it.
now this workds flawlessly...
thankyou all...

Related

Unable to perform any operation on data retrieved using curl in php

I am trying to get data from particular website. Initially I was trying to retrieve data using normal $.ajax() method but because of cross domain problem I drop that idea. Now I'm trying to get same data using PHP's curl function. I'm getting success in it, but I was expecting json response in return but I am getting some kind of json + some other string at the end of that json data. I was even trying to delete that padding with PHP's string operations but I am unable to perform any kind of operations on that data. So, is there any way of doing that? Even when I'm trying to store that $string variable in a log for any text file it is saving the html code not the respose posted below.
Here is my code:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/do/mapsearch/getResults_ajax");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'city=12&map_type=listing&latlongsearch=1&encrypted_input=UiB8IFFTIHwgUyB8IzIjICB8IG11bWJhaSB8IzMjICB8IE5SSSB8IFkgIzIxI3wgIHwgMSw0LDIsMyw5MCw1LDIyIHwgMTIgfCMxIyAgfCBPLEEsQiMzIyB8IDEsNCwyLDMsOTAsNSwyMiM1IyB8IE8sQSxCICMzMSN8ICA%3D&keyword=&sortby=&mapsearch=1&locality_array=null&building_id=&latitude=19.137212294689522&longitude=72.8479625817871&latlongsearchdistance=3&page=1');
curl_setopt($ch, CURLOPT_POST, 1);
$string = curl_exec($ch);
// it's not even printing these two lines
echo "<br /><br/><br/>";
echo "hie";
echo curl_error($ch);
curl_close($ch);
// tring to get type of response but not printing anything on web page
echo gettype($string);
?>
Here is the part of my response:
{"total":2987,"resultsCount":30,"results":[{"PROP_ID":"K19962871","SPID":19962871,"VERIFIED":"N","PROFILEID":"509882","SHORTLISTED":"N","TYPE_DISP":"Apartment","AREA_UNIT":"Sq.Ft.","AREA":580,"AREA_TYPE":"Super built-up ","LOCALITY_ID":4962,"BUILDING_ID":0,"IS_XID_ATTACHED":0,"PRICE_DISP":"86 Lac","CITY":"Mumbai Andheri-Dahisar","LOCALITY":"Jogeshwari (West)","SOCIETY_NAME":"Off S.v. Road","PROP_NAME":"Off S.V. Road","LISTING":"P","BEDROOM_NUM":1,"LATITUDE":"19.1364893","LONGITUDE":"72.8488709","PROP_INFO":{"class_label":"Dealer","dealer_url":"\/sainath-estate-mumbai-andheri-dahisar-drid-509882","text":"Sainath Estate","link":true,"vcard":false},"BLDNG_INFO":{"name":"Off S.v. Road","link":null,"label":"Society :","cls":"fwn ","lcls":null},"DEFAULT_THUMB":{"url":"http:\/\/static.99acres.com\/images\/mapsearch\/nophoto.jpg","type":"noPhoto"},"MAPPED":"N","AVAILABILITY":"Ready to Move","FURNISH":""}],"encrypted_input":"UiB8IFFTIHwgUyB8IzIjICB8IG11bWJhaSB8IzMjICB8IE5SSSB8IFkgIzIxI3wgIHwgMSw0LDIsMyw5MCw1LDIyIHwgMTIgfCMxIyAgfCBPLEEsQiMzIyB8IDEsNCwyLDMsOTAsNSwyMiM1IyB8IE8sQSxCICMxMiN8ICB8IDEgfCAxOS4xMzcyMTIyOTQ2ODk1MjIgfCA3Mi44NDc5NjI1ODE3ODcxIHwgMyAjMTQjfCAg","list_vlnk":"\/property-in-mumbai-ffid?orig_property_type=1,4,2,3,90,5,22&class=O,A,B&search_type=QS&search_location=NRI&pageid=QS&keyword_orig=mumbai&property_type=1,4,2,3,90,5,22","html2":"
Please any suggestions?
Thank you..

How to get content of a website which calls a JSON file using PHP/cURL

There is a supermarket website and I need to get list of product name and price data.
The website is: http://www.sanalmarket.com.tr/kweb/sclist/30011-tum-meyveler
However, I cannot get this content with success. Every attempt finalized with a null result. I am not familiar with cURL, but it is recommended me to overcome this issue. As I see, the product list is called with Ajax - JSON and for this reason, I should follow requests to see JSON files and their contents using PHP. ...But how?
Thank you in advance.
The code I tried:
<?php
$url="https://www.sanalmarket.com.tr/kweb/sclist/30011-tum-meyveler";
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
curl_close($ch);
var_dump(json_decode($result, true));
?>
Your curl request did work and you are getting html response in the $result variable. The problem is that you are treating the html response string like a valid JSON string.
instead of
var_dump(json_decode($result, true));
try
var_dump($result);
Here $result is not a valid JSON string. It is a string containing the html that the server responded. So you cannot parse it directly into an array or object without using a html parser.

Use cURL to call API in PHP

I have the following codes, however, it does not return anything-a blank page. But if I plug in the right parameters and place the entire link on web browser, it would return the results I want. I don't want to use file_get_contents because I need to use this function for other API calls that cannot return results by entering the entire link on the address bar. Thanks for helping.
<?php
$data_string ='<HotelListRequest><hotelId>A HOTEL</hotelId></HotelListRequest>';
// Tell CURL the URL of the recipient script
$curl_handle = curl_init ();
curl_setopt ($curl_handle, CURLOPT_URL, 'http://api.ean.com/ean-services/rs/hotel/v3/info?minorRev=4&cid=MYID&apiKey=MYAPIKEY&customerSessionId=&locale=en_US&currencyCode=USD&xml=');
// This section sets various options. See http://www.php.net/manual/en/function.curl-setopt.php
curl_setopt ($curl_handle, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt ($curl_handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($curl_handle, CURLOPT_POST, true);
curl_setopt ($curl_handle, CURLOPT_POSTFIELDS, $data_string);
// Perform the POST and get the data returned by the server.
$result = curl_exec ($curl_handle);
// Close the CURL handle
curl_close ($curl_handle);
echo $result;
?>
If you put everything into a browser and it works, you're using GET data. Does the service support the use of POST data (which is what you're sending in your example)? Have you tried sending all the data via the CURLOPT_URL?
Also, you'll want to change the data string to
"xml=".$data_string
and possibly you're other arguments as well (depending on the API).
According to http://php.net/manual/en/function.curl-setopt.php :
The full data to post in a HTTP "POST" operation. To post a file,
prepend a filename with # and use the full path. The filetype can be
explicitly specified by following the filename with the type in the
format ';type=mimetype'. This parameter can either be passed as a
urlencoded string like 'para1=val1&para2=val2&...' or as an array with
the field name as key and field data as value. If value is an array,
the Content-Type header will be set to multipart/form-data. As of PHP
5.2.0, value must be an array if files are passed to this option with the # prefix.
So you should modify you $data_string variable content to match the required format.

Send cUrl data without vars array

I try to post data without setting variable or array. I don't know it's possible ?
When i send $data = array('var_name'=>'var_val') everything works fine, but when i set $data ='to send' i don't get any post data.
$data = 'sample data to send';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
//curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-type: application/json'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$resp = curl_exec($ch);
From the manual:
CURLOPT_POSTFIELDS
The full data to post in a HTTP "POST" operation. To post a file, prepend a filename with # and use the full path. The filetype can be explicitly specified by following the filename with the type in the format ';type=mimetype'. This parameter can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value. If value is an array, the Content-Type header will be set to multipart/form-data. As of PHP 5.2.0, value must be an array if files are passed to this option with the # prefix.
Simple strings are assumed to be key/value pairs by the other end. Whatever the other end is doesn't see the un-keyed value you're passing. If this was a GET instead of a POST, I'd say just inspect the query string. As that isn't the case, you'll want to send the data with a key and a value instead, or figure out how the other end reads raw POST data. If the other end is PHP, there are at least two ways to do this.
The reason is "to send" becomes a key for $_POST data. To be able to see it, in the PHP file which is $url, do var_dump($_POST); This should show that key value on output. But as you can expect, it doesn't have any value.
You can take the data you have written in POSTFIELDS as raw with
$yourPostedData = file_get_contents('php://input');
POST request does not necessarily contain pairs of variable = value. Sometimes it contains raw data. To access it, you need to use the variable $HTTP_RAW_POST_DATA that will be filled with raw POST data in that case.

cURL returning XML or JSON

I've got a form say here - http://example.com/palreg.php
Once people register I'll be sending them an email with the link that will allow them to edit their details (I know it's a crazy way of doing things, but I am working on someone else's code so don't mind) for instance the url as such http://example.com/palreg.php?paliD=1234, and when they go to that page the form will be populated with their information so that they can make changes.
Now the problem is that the DB is in a different site and the information has to be passed to that site to perform a select action, to do so I use cURL to send the information like so
$url = "http://example2.com/processXML.php";
$xmlStr will be like this
<table>tab_name</table>
<action>select</action>
<palid>1234</palid>
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, 'xmlstr='.$xmlStr);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
On the other end (http://example2.com/processXML.php) I convert the xml to an array and perform the query to select pal information based on the id sent.
The real question now is how do I send the retrieved pal information (as xml or json or array) back so that i can populate the form with the returned data.
Also can I do a return $dataArray; in processXML.php and be able to grab it?
OK to make things a bit clearer, what I do in processXML.php is
retrieve the result set and do this
print json_encode($resultArray);
not should I print or return
Thank you, and do let me know if things aren't clear.
just encode it as you want, and echo it to the page. your $data= will contain the echoed contents. Personal preference has been to use JSON since it's so easy to throw around. as in
//Bunch of DB stuff..
$row=mysql_fetch_however_you_handle_it();
echo json_encode($row);
//on your receiving end, that just did the cURL send,
$row=json_decode($data,true);//decode the JSON straight into an array...
When you pull the information from the database and process it in processXML.php, add the results to an array, use json_encode() to convert the array to JSON, and then echo the results to the page.
Just echo out the data you need to send back to the form, in your format of choice, and fetch that response in thepalreg.php.

Categories