how to post xml with curl with php GET variables? - php

the script will post xml content to a url, and i need to include the php GET variables (eg. $RegionId), pls advise how to.
$RegionId = $_GET["RegionId"];
// xml data
$xml_data ='<AvailabilitySearch>
<RegionId xmlns="http://www.reservwire.com/namespace/WebServices/Xml">$RegionId</RegionId>
<HotelId xmlns="http://www.reservwire.com/namespace/WebServices/Xml">0</HotelId>
<HotelStayDetails xmlns="http://www.reservwire.com/namespace/WebServices/Xml">
</AvailabilitySearch>
';
// assigning url and posting with curl
$URL = "http://roomsxmldemo.com/RXLStagingServices/ASMX/XmlService.asmx";
$ch = curl_init($URL);
............
............
............
$RegionId is not posted on the script, how to use the GET or POST variable on that xml content?

Hope this will help You
$RegionId = $_GET["RegionId"];
// xml data
$xml_data ='<?xml version="1.0" encoding="UTF-8"?><AvailabilitySearch>
<RegionId xmlns="http://www.reservwire.com/namespace/WebServices/Xml">{$RegionId}</RegionId>
<HotelId xmlns="http://www.reservwire.com/namespace/WebServices/Xml">0</HotelId>
<HotelStayDetails xmlns="http://www.reservwire.com/namespace/WebServices/Xml">
</AvailabilitySearch>
';
// assigning url and posting with curl
$URL = "http://roomsxmldemo.com/RXLStagingServices/ASMX/XmlService.asmx";
$headers = array(
"Content-type: text/xml",
"Content-length: " . strlen($xml_data),
"Connection: close",
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$UR);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_data);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$data = curl_exec($ch);
curl_close($ch);
echo $data;

Just add your GET vars to url.
$URL = "http://roomsxmldemo.com/RXLStagingServices/ASMX/XmlService.asmx?var1=val1&var2=val2";

Well, merely you can wrap your xml content in double quotes and substitute necessary variables.
$id = (isset($_GET['id'])) ? $_GET['id'] : '';
xml_data = "<AvailabilitySearch>
<RegionId xmlns=\"http://www.reservwire.com/namespace/WebServices/Xml\">$rid</RegionId>
<HotelId xmlns=\"http://www.reservwire.com/namespace/WebServices/Xml\">0</HotelId>
<HotelStayDetails xmlns=\"http://www.reservwire.com/namespace/WebServices/Xml\">
</AvailabilitySearch>";
Value of $id variable will be in xml content. And you can post this message. But, don't forget to shield inner double quotes with additional slashes in your xml.

Related

Razorpay OrderId not fetching paymentId using curl Php [duplicate]

I'm tyring to use curl to print a return from a url. The code I have so far looks like this:
<?php
$street = $_GET['street'];
$city = $_GET['city'];
$state = $_GET['state'];
$zip = $_GET['zip'];
$url = 'http://eligibility.cert.sc.egov.usda.gov/eligibility/eligibilityservice';
$query = 'eligibilityType=Property&requestString=<?xml version="1.0"?><Eligibility xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="/var/lib/tomcat5/webapps/eligibility/Eligibilitywsdl.xsd"><PropertyRequest StreetAddress1="'.$street.'" StreetAddress2="" StreetAddress3="" City="'.$city.'" State="'.$state.'" County="" Zip="'.$zip.'" Program="RBS"></PropertyRequest></Eligibility>';
$url_final = $url.''.$url_query;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$query);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$return = curl_exec ($ch);
curl_close ($ch);
echo $return;
?>
the only obvious problem I know of it that the server being queried uses GET instead of POST. Are there GET alternatives to this method?
curl_setopt($ch, CURLOPT_POST, 0);
Curl uses GET by default. You were setting it to POST. You can override it if you ever need to with curl_setopt($ch, CURLOPT_HTTPGET, 1);
Use file_get_contents() function
file_get_contents
Or curl_setopt($ch, CURLOPT_HTTPGET, 1);
use
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => "http://yourlink.com",
CURLOPT_USERAGENT => 'Codular Sample cURL Request'));
All these years and nobody's given the right answer; the way to build a query string is to use http_build_query() with an array. This automatically escapes everything and returns a simple string.
$xml = '<?xml version="1.0"?><Eligibility xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="/var/lib/tomcat5/webapps/eligibility/Eligibilitywsdl.xsd"><PropertyRequest StreetAddress1="'.$street.'" StreetAddress2="" StreetAddress3="" City="'.$city.'" State="'.$state.'" County="" Zip="'.$zip.'" Program="RBS"></PropertyRequest></Eligibility>';
$data = [
"eligibilityType" => "Property",
"requestString" => $xml
];
$query = http_build_query($data);
$url .= "?$query";
You are missing a question mark in the URL.
Should be like:
$query = '?eligibilityType=Property&...';
Also, that XML in your URL needs encoding, e.g. use the urlencode() function in PHP.

Apple news API. PHP code for Connect and send json data

I am able to connect with the help of apple news api but I can't able to send data in json format.
My code is below.
but when I try to attach json file. I am getting signature failure message.
<?php
$channel_id = 'xxxxxxxxxxxxxxxxxx';
$api_key_id = 'xxxxxxxxxxxxxxx';
$api_key_secret = 'xxxxxxxxxxxxxxxx';
// use the correct values above
$data = file_get_contents('article.json');
$Content_type="application/json";
$url = 'https://news-api.apple.com/channels/'.$channel_id;
$date = gmdate('Y-m-d\TH:i:s\Z');
$canonical_request = 'GET'.$url.$date.$Content_type;
$key = base64_decode($api_key_secret);
$hashed = hash_hmac('sha256', $canonical_request,$key,true);
$signature = base64_encode($hashed);
echo $signature;
//curl options
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
$headers = array();
$headers[] = "Authorization: HHMAC; key={$api_key_id}; signature={$signature}; date={$date}";
$headers[] = "Content-Type: application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
//curl_setopt($ch, CURLOPT_POST, true);
//curl_setopt( $ch, CURLOPT_POSTFIELDS, $data);
//get result
$server_output = curl_exec ($ch);
curl_close ($ch);
print_r(json_decode($server_output));
?>
Since you are sending a GET request, you are incorrectly including the content type when building the canonical request.
This should work for you, then:
$canonical_request = 'GET'.$url.$date;
For reference, see Apple News API Reference: Setting Up MAC/HMAC Authentication:
Create a canonical version of the request as a byte-wise concatenation of the following:
The HTTP method (for example, GET or POST, in all caps)
The full URL of the request
The current date in ISO 8601 format
If the request is a POST request and it includes an entity, include the following:
The value of the Content-Type header
The full content of the entity

Parsing xml with php and curl - Expedia API

I'm wanting to extract some data from an API call I have made. Using PHP CURL.
Here is my code:
<?PHP
//use latest minorRev 14
$url ='http://api.ean.com/ean-services/rs/hotel/v3/list?minorRev=99';
$url .= '&apiKey=' . $apiKey;
$url .= '&cid=55505';
$url .= '&locale=en_US&city=Dallas&stateProvinceCode=TX&countryCode=US&numberOfResults=3';
$url .= '&searchRadius=50';
//using the cache returns results much faster
$url .= '&supplierCacheTolerance=MED_ENHANCED';
//dates and occupancy
$url .='&arrivalDate=09/04/2014&departureDate=09/05/2014&room1=2';
$header[] = "Accept: application/json";
$header[] = "Accept-Encoding: gzip";
$ch = curl_init();
curl_setopt( $ch, CURLOPT_HTTPHEADER, $header );
curl_setopt($ch,CURLOPT_ENCODING , "gzip");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
$response = json_decode(curl_exec($ch));
$response = curl_exec($ch);
?>
<html>
<body>
<table>
<Tr>
<TD>
<?PHP
$hotels = simplexml_load_file('http://api.ean.com/ean-services/rs/hotel/v3/list?minorRev=99&apiKey=7z6tduachrht362dpnsch34v&cid=55505&locale=en_US&city=Dallas&stateProvinceCode=TX&countryCode=US&numberOfResults=3&searchRadius=50&supplierCacheTolerance=MED_ENHANCED&arrivalDate=09/04/2014&departureDate=09/05/2014&room1=2');
echo $hotels;
?>
</TD>
</Tr>
</table>
Why am I not getting anything returned by using the simplexml_load_file function?
I was also following this as a guide - http://blog.teamtreehouse.com/how-to-parse-xml-with-php5
If you look closely the guide you've linked, you'll see that the guide tells you to do:
echo $mysongs->song[0]->artist;
This means that the return of the simplexml_load_file is not a simple string, it's an object, and you'll have to access its data. I'm not sure how to do it but it might look similar to this:
foreach($hotels as $hotel){
echo $hotel;
}
You'll have to read better the guide to use it.
As I said in the comment, anytime you're not sure how to access or use an object, running the program with the code die(var_dump($object)); can help you to get a lot of information of that object and how to access it.
Are you returning the $response from your simplexml_load_file correctly?
If yes, then remove this line from your code:
$header[] = "Accept-Encoding: gzip";
And remove the gzip from the CURLOPT_ENCODING. Instead use empty which means accept any encodings.
curl_setopt($ch,CURLOPT_ENCODING , "");
Also, before doing the json_decode over the response, just print it or save it into a file and observe that a valid json object is returned from the server or not.
And finally, debug yourself the curl request by enabling the verbose mode.
curl_setopt($ch,CURLOPT_VERBOSE, true);
The API you have is returning data in JSON format not XML.
$hotels = file_get_contents($url);
echo $hotels;
this is why simplexml_load_file will fail, you have to use json_decode instead
You parse JSON data this way:
$data_json = json_decode(file_get_contents($url));
$HotelListResponse = $data_json->{"HotelListResponse"};
$HotelList = $HotelListResponse->{"HotelList"};
$HotelSummary = $HotelList->{"HotelSummary"};
var_dump($HotelSummary);
and so forth
You can print the hotel name like this:
foreach($HotelSummary as $summary){
$hotelName = $summary->{"name"};
echo $hotelName."<br />";
}

Construct a PHP POST request with binary data

I'm trying to construct a PHP POST request that includes some binary data, following on from a previous StackOverflow question. The data is being submitted to this API call: http://www.cyclestreets.net/api/#addphoto
This is my PHP code:
$file = $_FILES['mediaupload'];
$file_field="#$file[tmp_name]";
$fields = array(
'mediaupload'=>$file_field,
'username'=>urlencode($_POST["username"]),
'password'=>urlencode($_POST["password"]),
'latitude'=>urlencode($_POST["latitude"]),
'longitude'=>urlencode($_POST["longitude"]),
'datetime'=>urlencode($_POST["datetime"]),
'category'=>urlencode($_POST["category"]),
'metacategory'=>urlencode($_POST["metacategory"]),
'caption'=>urlencode($_POST["description"])
);
$fields_string = http_build_query($fields);
echo 'FIELDS STRING: ' . $fields_string;
$url = 'https://www.cyclestreets.net/api/addphoto.json?key=$key';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec ($ch);
This is what my PHP file outputs:
FIELDS STRING: mediaupload=%40%2Fprivate%2Fvar%2Ftmp%2FphpHjfkRP&username=testing&password=testing&latitude=auto&longitude=auto&datetime=auto&category=cycleparking&metacategory=good&caption=
API RESPONSE: {"request":{"datetime":"1309886656"},"error":{"code":"unknown","message":"The photo was received successfully, but an error occurred while processing it."},"result":{}}
I believe this means that everything else about the request is OK, apart from the format of the binary data. Can anyone tell me what I am doing wrong?
CURL can accept a raw array of key=>value pairs for POST fields. There's no need to do all that urlencode() and http_build_query() stuff. Most likely the # in the array is being mangled into %40, so CURL doesn't see it as a file upload attempt.
$fields = array(
'mediaupload'=>$file_field,
'username'=> $_POST["username"),
etc...
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields);
The http_build_query function generates a URL encoded query string which means that the "#file.ext" is URL encoded in the output as a string and cURL doesn't know that you're trying to upload a file.
My advice would be not to include the file to upload in the http_build_query call and included manually in the CURLOPT_POSTFIELDS.
$file = $_FILES['mediaupload'];
$file_field="#$file[tmp_name]";
$fields = array(
'username'=>urlencode($_POST["username"]),
'password'=>urlencode($_POST["password"]),
'latitude'=>urlencode($_POST["latitude"]),
'longitude'=>urlencode($_POST["longitude"]),
'datetime'=>urlencode($_POST["datetime"]),
'category'=>urlencode($_POST["category"]),
'metacategory'=>urlencode($_POST["metacategory"]),
'caption'=>urlencode($_POST["description"])
);
$fields_string = http_build_query($fields);
echo 'FIELDS STRING: ' . $fields_string;
$url = 'https://www.cyclestreets.net/api/addphoto.json?key=$key';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, 'mediaupload=' . $file_field . '&' . $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec ($ch);

php upload xml to google api

I need some help with this problem, please.
For days I have been trying now.
The retrieving off feeds and parsing them is not really a problem, but
Uploading data in the form off xml is?
The code below is partially from the google docs samplecode also, but obviously it's not working.
I hope someone else is more into the google api workings, because I have no idea.
Currently, I am only attempting to add a tag to a photo in an album.
Once that works, I can probably do the rest also.
public function postTag() {
$query='smarty';
$this->updateOptie('tag', $query);
$feedUrl = $this->creeerFeedUrl('myalbum', false);
$picasa = $this->parseFeed( $feedUrl );
$gphoto = $picasa['gphoto'][0];
$gphotoid = $gphoto['id'];
//return $gphotoid;
////////////////////sofar no problem//////////////////
$tag = "mytag";
$data = "<entry xmlns='http://www.w3.org/2005/Atom'>
<title>$tag</title>
<category scheme=\"http://schemas.google.com/g/2005#kind\" term=\"http://schemas.google.com/photos/2007#tag\"/>
</entry>";
$albumid = 'myalbum';
$itemsFeedURL = $this->krijgPicasaBasisUrl(). "/albumid/$albumid/photoid/$gphotoid";
$len=strlen($data);
$headers = array(
"Authorization: GoogleLogin auth=" . $this->auth,
"GData-Version: 2",
'Content-Type: application/atom+xml',
"Content-Length: $len",
);
$ch = curl_init(); /* Create a CURL handle. */
/* Set cURL options. */
curl_setopt($ch, CURLOPT_URL, $itemsFeedURL);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
$result = curl_exec($ch); /* Execute the HTTP request. */
$info = curl_getinfo($ch);
curl_close($ch); /* Close the cURL handle. */
return $info;
thanks, rich
Your quoting is broken. The code as you posted in your quesion can't work, because $data contains unescaped double quotes ". You need to escape them all like so: \". If this is that way in the code, that may already be the problem.
Use echo curl_error() after the curl_exec() call to see whether something went wrong during the upload.

Categories