Place a php function into an XML request - php

I am trying to add the results from the while loop into an xml request. But it is not showing up correctly.. Below I first create a function, then I try to make that function work inside the xml request curl tag. It is hard to explain and easier to see:
//Getting room groups
function roomGroups(){
$i = 2;
while(isset($_GET['ad'.$i]))
{
$adult = $_GET['ad'.$i];
$child = $_GET['ch'.$i];
$childAge = $_GET['ch'.$i];
echo "<RoomGroup><Room><numberOfAdults>".$adult."</numberOfAdults><numberOfChildren>".$child."<childAges>".$childAge."</childAges></Room></RoomGroup>";
$i++;
}}
//Room availablility Request
$ch1 = curl_init();
$fp1 = fopen('room_request.xml','w');
curl_setopt($ch1, CURLOPT_URL, "http://api.ean.com/ean-services/rs/hotel/v3/avail?cid=379849&minorRev=13&apiKey=4sr8d8bsn75tpcuja6ypx5g3&locale=en_US&currencyCode=USD&customerIpAddress=67.20.125.193&customerUserAgent=Mozilla/5.0+(Windows+NT+6.1)+AppleWebKit/535.11+(KHTML,+like+Gecko)+Chrome/17.0.963.79+Safari/535.11&customerSessionId=0ABAA856-8502-E913-6982-E2210F904B72&xml=<HotelRoomAvailabilityRequest><hotelId>".$hid."</hotelId><arrivalDate>".$arrivalDate."</arrivalDate><departureDate>".$departingDate."</departureDate><RoomGroup><Room><numberOfAdults>".$adults."</numberOfAdults><numberOfChildren>".$children."</numberOfChildren><childAges>".$ages."</childAges></Room></RoomGroup>".roomGroups()."<includeDetails>true</includeDetails></HotelRoomAvailabilityRequest>");
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch1, CURLOPT_HTTPHEADER, array('Accept: application/xml'));
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch1, CURLOPT_FILE, $fp1);
$val1 = curl_exec($ch1);
curl_close($ch1);//Close curl session
fclose($fp1); //Close file overwrite
$avail = simplexml_load_file('room_request.xml');
//The url that is passing the data looks like this: /hotel_request.php?hid=370111&d=05/02/2012&a=04/30/2012&r=3&ad2=2&ch2=22=16,17,&ad3=3&ch3=33=7,13,16,&
I get nothing back. Any help on this would be GREATLY appreciated!

roomGroups() doesn't return anything, it just echos to the screen.
Try something like this:
function roomGroups(){
$i = 2;
$ret = '';
while(isset($_GET['ad'.$i])){
$adult = $_GET['ad'.$i];
$child = $_GET['ch'.$i];
$childAge = $_GET['ch'.$i];
$ret .= "<RoomGroup><Room><numberOfAdults>".$adult."</numberOfAdults><numberOfChildren>".$child."<childAges>".$childAge."</childAges></Room></RoomGroup>";
$i++;
}
return $ret;
}

Related

Curl and array values in curlopt_url does not work

i have a very weird issue with curl and url defined inside an array.
I have an array of url and i want perform an http GET on those urls with curl
for ($i = 0, $n = count($array_station) ; $i < $n ; $i++)
{
$station= curl_init();
curl_setopt($station, CURLOPT_VERBOSE, true);
curl_setopt($station, CURLOPT_URL, $array_station[$i]);
curl_setopt($station, CURLOPT_RETURNTRANSFER, true);
curl_setopt($station, CURLOPT_FOLLOWLOCATION, true);
$response = curl_exec($station);
curl_close($station);
}
If i define my $array_station in the way below
$array_station=array("http://www.example.com","http://www.example2.com");
the code above with curl working flawlassy,but since my $array_station is build in the way below (i perform a scan of directory searchin a specific filename, then i clean the url), the curl does not work, no error showed and nothing happens..
$di = new RecursiveDirectoryIterator(__DIR__,RecursiveDirectoryIterator::SKIP_DOTS);
$it = new RecursiveIteratorIterator($di);
$array_station=array();
$i=0;
foreach($it as $file) {
if (pathinfo($file, PATHINFO_FILENAME ) == "db_insert") {
$string = str_replace('/web/htdocs/', 'http://', $file.PHP_EOL);
$string2 = str_replace('/home','', $string);
$array_station[$i]=$string2;
$i++;
}
}
Doyou have some ideas? i'm giving up :-(
I'm on mobile right now so i cannot test it, but why are you adding a new line (PHP_EOL) to the url? Try to remove the new line or trim() the url at the end.
Add the lines of code below.
If there is a curl error it will report the error number.
If the request is made, it will show the HTTP request and response headers. The request is in $info and response header is in $head
for ($i = 0, $n = count($array_station) ; $i < $n ; $i++)
{
$station= curl_init();
curl_setopt($station, CURLOPT_VERBOSE, true);
curl_setopt($station, CURLOPT_URL, $array_station[$i]);
curl_setopt($station, CURLOPT_RETURNTRANSFER, true);
curl_setopt($station, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
$response = curl_exec($station);
if (curl_errno($station)){
$response .= 'Retreive Base Page Error: ' . curl_error($station);
}
else {
$skip = intval(curl_getinfo($station, CURLINFO_HEADER_SIZE));
$head = substr($response ,0,$skip);
$response = substr($response ,$skip);
$info = var_export(curl_getinfo($station),true);
}
echo $head;
echo $info;
curl_close($station);
}

curl_exec returns empty string

I'm still a bit new to using curl to pull data and I've recently started using Fiddler to help find what options need to be set.
I'm trying to see if I can pull an image from a site. I first hit a search page - I set the search parameters, then start hitting links in the results. When I attempt to go a link in one of the results for an image, I get an empty string returned from curl_exec().
The weird thing is - at one point, it worked - I got the data back and successfully saved the image locally. But then it stopped, and I have no idea what I was doing to have it working. Naturally, everything works OK in the browser. :(
I'm using Simple HTML DOM to parse through results and cUrl for the actual page requests. curl_error() does not show an error, curl_getinfo() thinks everything is OK too. It's probably something trivial, but I'm not sure how to troubleshoot it beyond where I am.
<?php
include 'includes/simple_html_dom.php';
$url = "http://nwweb.co.bell.tx.us/NewWorld.Aegis.WebPortal/Corrections/InmateInquiry.aspx";
// Get Cookie - ASP.NET_SessionId
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$r = curl_exec($ch);
preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $r, $matches);
$cookies = array();
foreach($matches[1] as $item)
{
parse_str($item, $cookie);
$cookies = array_merge($cookies, $cookie);
}
$sessionCookie = "ASP_NET_SessionId=".$cookies['ASP_NET_SessionId'];
// now load up page into Simple HTML DOM and get all inputs - ignore buttons and populate our dates
$startDate = "02%2F01%2F2000";
$endDate = "02%2F07%2F2016";
$getInputs = str_get_html($r);
$inputs = $getInputs->find('input');
$inputs_array = array();
$buttons_array = array();
for ($i=0; $i<count($inputs); $i++)
{
if ($inputs[$i]->type != "submit")
{
$inputs_array[$inputs[$i]->id] = $inputs[$i]->value;
if (stripos($inputs[$i]->id, "FromDate") > 0)
$inputs_array[$inputs[$i]->id] = $startDate;
if (stripos($inputs[$i]->id, "ToDate") > 0)
$inputs_array[$inputs[$i]->id] = $endDate;
}
}
// build up our curl data - includes hidden inputs, our to & from dates, plus the Search button
$curl_data = http_build_query($inputs_array)."&ctl00%24DefaultContent%24uxSearch=Search";
// POST the data, include session cookie
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $curl_data);
curl_setopt($ch, CURLOPT_COOKIE, $sessionCookie);
$response = curl_exec($ch);
// this shows that we can get data
// find the links from the HTML
$htmlDom = str_get_html($response); // load up Simple HTML DOM
// get the table of results
$divTable = $htmlDom->find('div#ctl00_DefaultContent_uxResultsWrapper',0)->find('table',0);
$rows = $divTable->find('tr');
for ($i=1; $i<count($rows);$i++)
{
if ($i>3) break; // limit the length of script for debugging
$link = $rows[$i]->find('td',1)->find('a',0)->href;
// build up query to get inmate details from the link above
$url = "http://nwweb.co.bell.tx.us/NewWorld.Aegis.WebPortal/Corrections/".$link;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_COOKIE, $sessionCookie);
$page = curl_exec($ch);
$pageData = str_get_html($page);
// Now find the Photo, there's a thumb in div.BookingPhotos
// It is linked to a full size image, the link is of the form http://nwweb.co.bell.tx.us/NewWorld.Aegis.WebPortal/GetImage.aspx?ImageKey=17C030IS, but in the href, it has ../GetImage.aspx?ImageKey=xxxx
$photoLink = $pageData->find('div.BookingPhotos',0)->find('a',0)->href;
// get rid of .. and put the base URL on the front
$imgLink = str_replace("..", "http://nwweb.co.bell.tx.us/NewWorld.Aegis.WebPortal", $photoLink);
// now attempt to pull the image
$ch = curl_init($imgLink);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_COOKIE, $sessionCookie);
// here is the PROBLEM - NO DATA RETURNED
$imgData = curl_exec($ch); // I get a header back, but NO data
}
?>

curl response showing nothing using within php

i am trying to get data from a url using curl. i've made a recursive function for this. i get the data successfully , but the problem what i am facing is that when no result is found against curl call, then the page show me nothing, only a blank page is shown.. no error at all. i've used var_dump() too for testing the response. but found nothing.
here is my recursive function
function recursive_get_scrap($offset, $page_size, $urls, $original_array){
ini_set('max_execution_time', 1800);
$of_set = $offset;
$pg_size = $page_size;
$off_sets = 'offset='.$of_set.'&page_size='.$pg_size.'';
$url = $urls.$off_sets;
$last_correct_array = $original_array;
$ch1 = curl_init();
// Disable SSL verification
curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch1, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch1, CURLOPT_URL,$url);
// Execute
$result2 = curl_exec($ch1);
$info = curl_getinfo($ch1);
if(curl_errno($ch1))
{
echo 'error:' . curl_error($ch1);
//return $last_correct_array;
}
// Closing
curl_close($ch1);
if(!$result2 || strlen(trim($result2)) == 0 || $result2 == false){
echo 'no array';
}
if(isset($result2) && !empty($result2)){
echo 'in recursive function <br>';
$a1 = json_decode( $original_array, true );
$a2 = json_decode( $result2, true );
$temp_array = array_merge_recursive($a1, $a2 );
$last_correct_array = $temp_array;
$offset += 100;
$page_size = 100;
recursive_get_scrap($offset, $page_size, $urls, json_encode($last_correct_array));
}
}
now what i only want it that if noting is get against curl call then no array message should be displayed.
Use this option to curl_setopt():
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
This will make curl_exec return the data instead of outputting it.
To see if it was successful you can then check $result and also
curl_error().

Processing CSV through php function

I made a PHP function that works with an API to show me the dollar balance of an account. This function is called: get_balance
function get_balance($account){
$url = 'http://mycompaniesurl.com/' . $account; // url of website
global $response;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 3);
$response = curl_exec($ch);
curl_close($ch);
}
The function get_balance returns the output in the variable $response
I'm certain that the function works, so I have no questions on that part. However, I'm trying to process accountnumbers written down in a CSV file. I call the CSV file with the following code:
$file = new SplFileObject("test.csv");
$file->setFlags(SplFileObject::READ_CSV);
$data = call_user_func_array('array_merge', iterator_to_array($file));
$data = array_combine(range(1, count($data)), $data);
extract($data, EXTR_PREFIX_ALL, 'variable');
I'm testing my code with a csv file called test.csv, containing 4 addresses (first one has a balance of 0, other 3 have a balance of >0).
With the following code I get the balance with the accountnumber printed to my screen:
get_balance($data[2]);
if ($response > 0){
echo $response,"---------------",$data[2];
}
Because $data[1] has a balance of 0, nothing is printed. $data[2],$data[3] and $data[4] have a balance of more than 0, so they do return the balance together with the accountnumber.
Now what my question is; is there a way to 'automatically' do this? Something like
get_balance($data[]);
seems to not work. The CSV that this php file has to process is about ~1000 accountnumber and may have more in the future, so typing a get_balance($data[1]) up to get_balance($data[999]) will be a time consuming business.
Is there a (simple) way to apply the function to ALL the $data[] ?
Yes, there is, called array_map:
$balanced_data = array_map("get_balance", $data);
This will leave $balanced_data empty, because at the moment get_balance has no return, but uses a global variable. Change it to something like this
function get_balance($account){
$url = 'http://mycompaniesurl.com/' . $account; // url of website
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 3);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
If you don't want to or can't change get_balance, you will need a workaround like this
$max = count($data);
for ($i=0; $i<$max; $i++) {
$response = 0; // reset to make sure we get a new value
get_balance($data[$i]);
$balanced_data[$i] = $response;
}

Getting all root elements that contain child element with certain string in xml

Hi I am trying to return only a certain element from xml.. it is easier to explain like this:
<HotelList activePropertyCount="129" size="20">
<HotelSummary ubsScore="820" order="0">
<hotelId>121196</hotelId>
<name>ME Cancun - Complete ME All Inclusive</name>
<address1>Boulevard Kukulkan Km 12</address1>
<city>Cancun</city>
<postalCode>77500</postalCode>
<countryCode>MX</countryCode>
</HotelSummary>
</HotelList>
There are a bunch of these all with different hotelID. I need to get the <HotelSummary> that has the child element of <hotelID>121196</hotelID>. I can not figure out how to do this. I am using php and this is all I have so far:
<?
$post_string = 'type=xml&cid=55505&minorRev=13&apiKey=4sr8d8bsn75tpcuja6ypx5g3&locale=en_US&currencyCode=USD&customerIpAddress=10.184.2.9&customerUserAgent=Mozilla/5.0+(Windows+NT+6.1)+AppleWebKit/535.11+(KHTML,+like+Gecko)+Chrome/17.0.963.79+Safari/535.11&customerSessionId=&xml=<HotelListRequest><arrivalDate>04/05/2012</arrivalDate><departureDate>04/07/2012</departureDate><RoomGroup><Room><numberOfAdults>2</numberOfAdults></Room><Room><numberOfAdults>2</numberOfAdults><numberOfChildren></numberOfChildren></Room></RoomGroup><city>Cancun</city><countryCode>MX</countryCode><supplierCacheTolerance>MED_ENHANCED</supplierCacheTolerance></HotelListRequest> ';
$path = "http://api.ean.com/ean-services/rs/hotel/v3/list"; //Relative path to the file with $_POST parsing
$ch = curl_init($path);
$fp = fopen('room.xml','w');
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string); //Send the data to the file
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/xml'));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FILE, $fp);
$val = curl_exec($ch);
curl_close($ch);//Close curl session
fclose($fp); //Close file overwrite
$data = simplexml_load_file('room.xml');
$info=$data->HotelList->HotelSummary->hotelId="123658";
$rating=$info->hotelRating;
echo $rating;
?>
Thank you in advance!!!
Loop through and look for the specific id.
foreach($data->HotelList->HotelSummary as $hotel) {
if ($hotel->hotelId == 121196) {
// This is it.
break;
}
}

Categories