Is it possible to send a multi-associative array to a page using cURL in php?
I am able to pass an array, but the following happens:
// Open Connection
$ch = curl_init();
// Set the URL
curl_setopt($ch, CURLOPT_URL, $this->config['submission']['eyerys']);
// Set the number of fields being sent:
curl_setopt($ch,CURLOPT_POST,count($this->call['info']));
// The string to send:
curl_setopt($ch,CURLOPT_POSTFIELDS,$string);
// Return transfer:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// SSL verification:
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
// Execute the post:
$result = curl_exec($ch);
$this->pre($result);
// Close connection:
$curl_close($ch);
I get the following output:
Array
(
[info] => Array
[answers] => Array
[errors] => Array
)
Nope, since curl cannot know how you want to encode it. Not every server-side language/framework uses the same way. I think PHP is the only language where the user can create an array by simply sending data with keys containing []. For example. in the python world one would just send the same value twice and then use a different function (such as .getlist('key') - depends on the framework though) to access the array instead of just a single value.
If you have control over the remote script, consider using something standardized such as JSON. Instead of sending a formencoded POST string either send a pure JSON body or a single formencoded POST value containing the JSON.
If you don't, you'll most likely have to encode the POST data on your own.
Related
Hello I am getting json response from web using php curl. Response which I am getting is a bulk amount of data. Now I want to store some of the specific data into an array and print it in table form using php, like name, status, label etc. How can I do it?
$url = "";
$ch = curl_init();
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url);
$result = curl_exec($ch);
echo ($result);
curl_close($ch);
if you are getting a JSON response, use json_decode() to make it php readable. To make it an array (I would), use the true parameter like json_decode($result,true) and then manipulate the date from that array.
JSON-decode (php manual)
I got stuck while trying to set up cURL to retrieve data from other site(s)
Here is my situation.
I have 2 websites :
A
B
Website A sent data to website B as json format.
Of course, website A will have to encode all of it data before sending out - that's done.
Let the :
username = test
password = 1234
Website B just need run this command
curl --user test:1234 http://localhost/api/
They will then get the json file, and make anything out of it.
But, what if I have to do a mutiple cURL request.
SO I want to write a php script to do that.
This is what I have so far :
<?php
$ch = curl_init("http://localhost/api/");
$fp = fopen("api.txt", "w");
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
?>
Questions
While doing it this way, I am not sure how to configure the username and password.
After, knowing where to set the username and password, where should I do the decoding of the json ?
After that, how do I display those data that I just decoded in a HTML/PHP format ?
How do I test it ?
Set the username and password
Website B is using HTTP Basic Authentication. This is a authentication method via HTTP headers. You'll have to set the username and password in the Authorization header. This can be done With the cUrl module for PHP like this:
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
Decode your result
Assuming you just need the JSON data that website B is returning. Use the following option. It will make curl_exec() return the HTTP body instead of outputting it directly.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
For the list of options that can be used with the PHP curl module check the documentation on curl_setopt(). Now you are ready to make your request with cUrl using curl_exec() like this:
$body = curl_exec($ch);
Then decode the JSON data, for the sake of simplicity lets decode it to a PHP array:
$data = json_decode($body, true);
Test your code
In my opinion PHP is not a language which offers great testing features. Putting that aside, most of the time I test my code in an interactive shell. To start testing your scenario in an interactive shell you should have PHP CLI installed on your system. In linux this is straight forward. Start an interactive PHP shell with the following command:
php -a
Now you can start putting together your scenario.
php > $ch = curl_init('http://echo.jsontest.com/key/value/one/two');
php > curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
php > $body = curl_exec($ch);
php > var_dump($body);
string(39) "{
"one": "two",
"key": "value"
}
"
php > $data = json_decode($body, true);
php > print_r($data);
Array
(
[one] => two
[key] => value
)
You can configure username and password like this
//cURL Options
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_USERPWD => 'test:1234', // username:test pass:1234
CURLOPT_HTTPHEADER => array(‘Content-type: application/json’) ,
CURLOPT_POSTFIELDS => $json_string
);
// Setting curl options like this
curl_setopt_array( $ch, $options );
// Getting results
$result = curl_exec($ch); // Getting jSON result string
How do you test it?
I would put all that in a .php file and call it on the browser to debug to keep it simple.
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.
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¤cyCode=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¶2=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.
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¶2=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.