I need to put a string of data like so: '< client>...<\client>' onto an XMl server (example url:'http://example.appspot.com/examples') using PHP.
(Context: Adding a new client's details to the server).
I have tried using CURLOPT_PUT, with a file and with just a string (since it requires CURLOPT_INFILESIZE and CURLOPT_INFILE) but it does not work!
Are there any other PHP functions that could be used to do such a thing? I have been looking around but PUT requests information is sparse.
Thanks.
// Start curl
$ch = curl_init();
// URL for curl
$url = "http://example.appspot.com/examples";
// Put string into a temporary file
$putString = '<client>the RAW data string I want to send</client>';
/** use a max of 256KB of RAM before going to disk */
$putData = fopen('php://temp/maxmemory:256000', 'w');
if (!$putData) {
die('could not open temp memory data');
}
fwrite($putData, $putString);
fseek($putData, 0);
// Headers
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Binary transfer i.e. --data-BINARY
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
// Using a PUT method i.e. -XPUT
curl_setopt($ch, CURLOPT_PUT, true);
// Instead of POST fields use these settings
curl_setopt($ch, CURLOPT_INFILE, $putData);
curl_setopt($ch, CURLOPT_INFILESIZE, strlen($putString));
$output = curl_exec($ch);
echo $output;
// Close the file
fclose($putData);
// Stop curl
curl_close($ch);
since I haven't worked with cURL so far I can't really answer to that topic. If you'd like to use cURL I'd suggest looking at the server log and see what actually didn't work (so: Was the output of the request really what it's supposed to be?)
If you don't mind switching over to another technology/library I'd suggest you to use the Zend HTTP Client which is really straight forward to use, simple to include and should satisfy all your needs. Especially as performing a PUT Request is as simple as that:
<?php
// of course, perform require('Zend/...') and
// $client = new Zend_HTTP_Client() stuff before
// ...
[...]
$xml = '<yourxmlstuffhere>.....</...>';
$client->setRawData($xml)->setEncType('text/xml')->request('PUT');
?>
Code sample is from: Zend Framework Docs # RAW-Data Requests
Another way to add string body to the PUT request with CURL in PHP is:
<?php
$data = 'My string';
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); // Define method type
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // Set data to the body request
?>
I hope this helps!
Related
:)
I'm trying to send an XML using curl but not as post parameter. what I mean is this.
for example.
the receiving side of that XML won't be able to recieve the XML using $_POST variable.
he will need to use the following code:
$xmlStr=null;
$file=fopen('php://input','r');
$xmlStr=fgets($file);
I want to be able to send an xml string using curl via https.
so the following would be wrong:
public static function HttpsNoVerify($url,$postFields=null,$verbose=false) {
// Initialize session and set URL.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
// Set so curl_exec returns the result instead of outputting it.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
if ($postFields !=null) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
}
if ($verbose) {
curl_setopt($ch, CURLOPT_VERBOSE, 1);
}
// Get the response and close the channel.
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
because here i can use HttpsNoVerify($url,array('xml_file'=>'xml..')); and that
will paste it as post parameter. and i want it as post output.
so please I hope i explained myself properly and I explained exactly what I don't want to do.
how can I do what i want to do?
thanks! :)
kfir
Just directly pass the xml string as second parameter instead of an associative array item,
HttpsNoVerify($url, 'xml ..');
This will eventually call
curl_setopt($ch, CURLOPT_POSTFIELDS, "xml ...");
Which will be put in php://input for the remote server.
In PHP, how can I pass an Object (actually an Array) from one Site to another Site (by not losing its original Object Structure and Values)?
How to PASS/SEND from the host site
NOT to pull from the destination site
I want to pass directly from the automated script by NOT using HTML and web forms.
Any suggestion, please.
The best way to do that is to use json_encode():
file_get_contents('http://www.example.com/script.php?data='.json_encode($object));
on the other side:
$content = json_decode($_GET['data']);
or send it using cURL
$url = 'http://www.example.com/script.php';
$post = 'data='.json_encode($object);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_exec($ch);
on the other side:
$content = json_decode($_POST['data']);
You can convert it to JSON and then convert it back to the PHP object. This is very easy when it is an array. You can just use json_encode($array) and json_decode($json)on the other site. I would send the data via POST because the limit length of GET: Is there a limit to the length of a GET request?
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¤cyCode=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¤cyCode=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!!!
my service provider has given me following piece of PHP code for accessing his service. I need help in converting to C lang code for use in my application. The code is using curl module to post on to a site.
pls advise.
<?php
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, "http://api.mVaayoo.com/mvaayooapi/MessageCompose?user="myusername":"mypassword"&senderID=TEST SMS&receipientno="phonenum"&msgtxt=This is a test from mVaayoo API&state=4");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "user=$user&senderID=$senderID&receipientno=$receipientno&cid=$cid&msgtxt=$msgtxt");
$buffer = curl_exec($ch);
if(empty ($buffer))
{ echo " buffer is empty "; }
else
{ echo $buffer; }
curl_close($ch);
?>
Use libcurl with it's C-interface. The remainer is good old C-style-string-handling.
Your example libcurl program in the comment looks good, except that for a POST you need to install a CURLOPT_READFUNCTION, not a CURLOPT_WRITEFUNCTION. But if you just want to post a static buffer, use CURLOPT_POSTFIELDS instead of a callback function.
I'm having a little trouble updating backgrounds via Twitter's API.
$target_url = "http://www.google.com/logos/11th_birthday.gif";
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
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, 10);
$html = curl_exec($ch);
$content = $to->OAuthRequest('http://twitter.com/account/update_profile_background_image.xml', array('profile_background_image_url' => $html), 'POST');
When I try to pull the raw data via cURL or file_get_contents, I get this...
Expectation Failed The expectation given in the Expect request-header
field could not be met by this server.
The client sent
Expect: 100-continue but we only allow the 100-continue expectation.
OK, you can't direct Twitter to a URL, it won't accept that. Looking around a bit I've found that the best way is to download the image to the local server and then pass that over to Twitter almost like a form upload.
Try the following code, and let me know what you get.
// The URL from an external (or internal) server we want to grab
$url = 'http://www.google.com/logos/11th_birthday.gif';
// We need to grab the file name of this, unless you want to create your own
$filename = basename($url);
// This is where we'll be saving our new file to. Replace LOCALPATH with the path you would like to save the file to, i.e. www/home/content/my_directory/
$newfilename = 'LOCALPATH' . $filename;
// Copy it over, PHP will handle the overheads.
copy($url, $newfilename);
// Now it's OAuth time... fingers crossed!
$content = $to->OAuthRequest('http://twitter.com/account/update_profile_background_image.xml', array('profile_background_image_url' => $newfilename), 'POST');
// Echo something so you know it went through
print "done";
Well, given the error message, it sounds like you should load the URL's contents yourself, and post the data directly. Have you tried that?