I am trying to get the parent element, I think of an XML tag. Basically I need to go through multiple <HotelRoomResponse> results and find this parent tag that contains a child tag with this exact number value: <roomTypeCode>17918</roomTypeCode> I am not sure how to do this or what would be the best way. Because I then need to get ALL the information in that specific <HotelRoomResponse>. Here is an example XML response:
<HotelRoomResponse>
<cancellationPolicy> </cancellationPolicy>
<rateCode>200482409</rateCode>
<roomTypeCode>17918</roomTypeCode>
<rateDescription>
Deluxe Sunset View - All Inclusive-Up to $300Resort Credit
</rateDescription>
<roomTypeDescription>
Deluxe Sunset View - All Inclusive-Up to $300Resort Credit
</roomTypeDescription>
<supplierType>E</supplierType>
</HotelRoomResponse>
So there are various of these result types and I need to loop through it and find this specific one.
Here is how I am connecting to the XML:
$ch = curl_init();
$fp = fopen('room_request.xml','w');
curl_setopt($ch, CURLOPT_URL, "http://api.ean.com/ean-services/rs/hotel/v3/avail?cid=55505&minorRev=13&apiKey=4sr8d8bsn75tpcuja6ypx5g3&locale=en_US¤cyCode=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=<HotelRoomAvailabilityRequest><hotelId>".$hid."</hotelId><arrivalDate>05/14/2012</arrivalDate><departureDate>05/18/2012</departureDate><RoomGroup><Room><numberOfAdults>3</numberOfAdults><numberOfChildren>0</numberOfChildren><childAges>0</childAges></Room></RoomGroup><includeDetails>true</includeDetails></HotelRoomAvailabilityRequest>");
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
$avail = simplexml_load_file('room_request.xml');
Any ideas are welcome.
To find all HotelRoomResponse nodes which has a roomTypeCode child node with the value '17918', use the following:
$match = $avail->xpath("/HotelRoomResponse[child::roomTypeCode[text() = '17918']]");
EDIT: $match will be an array holding all matches.
Ok figured it out!!!! Here is what I used to get a node with text = value. Then I got all sibling elements.
// load as file
$contents = new SimpleXMLElement($source,null,true);
$result = $contents->xpath('HotelRoomResponse[roomTypeCode="17918"]');
foreach($result as $key=>$node)
{
$cancelPolicy = $node->cancellationPolicy;
}
$xml = new SimpleXMLElement('room_request.xml');
/* Search for <HotelRoomResponse><roomTypeCode> */
$result = $xml->xpath('/HotelRoomResponse/roomTypeCode');
Result will give you a list of nodes you can then check and get the parent node if appropriate
see here http://www.php.net/manual/en/simplexmlelement.xpath.php
Edit 2.
Key was the namespace
<?php
$ch = curl_init();
$fp = fopen('room_request.xml','w');
curl_setopt($ch, CURLOPT_URL, "http://travellinginmexico.com/test/room_request.xml");
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
$xml = new SimpleXMLElement(file_get_contents('room_request.xml'));
/* Search for <HotelRoomResponse><roomTypeCode> */
$xml->registerXPathNamespace('ns2', 'http://v3.hotel.wsapi.ean.com/');
$result = $xml->xpath("HotelRoomResponse[child::roomTypeCode[text() = '153725']]");
foreach($result as $obj=>$node)
{
var_dump($node->roomTypeCode);
}
With the example you sent will get specific information
Related
How can I remove firebase specific data? I use the
php Kreait\Firebase library.
$fg = $database->getReference('raw_check_out')->orderByChild('reciptno')->equalTo($recipt)->getSnapshot();
$reb = $fg->getValue();
$fg->remove();
but this is not working.
Based on your code example:
$fg = $database
->getReference('raw_check_out')
->orderByChild('reciptno')
->equalTo($recipt)
->getSnapshot();
Here $fg does not hold the reference, but the snapshot.
If you want to remove the reference after you have retrieved the data you need, you need the reference itself:
$fg = $database->getReference('raw_check_out');
$query = $fg->orderByChild('reciptno')->equalTo($recipt);
$reb = $query->getSnapshot()->getValue();
$fg->remove();
This function is for unsubscribing users if you want to remove "user-id-8776" and your structure is like:
public function unsubscribe($uid)
{
$ref = $this->database->getReference()->getChild('users')->getChild($uid)->orderByChild($uid)->getReference();
$path = $ref->getUri()->getPath();
$ref->remove();
}
For any other data is more or less the same, you just have to find the reference of data you want to delete it and then you can remove it.
Check Image
You have another option to resolve this problem. This solution given below:
$url = "https://<projectID>.firebaseio.com/chatList/".<jsonFileName>."json";
$ch = curl_init();
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/plain'));
$result = curl_exec($ch);
curl_close($ch);
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
}
?>
This example only displayed a blank page for me.
This one did as well.
I've got the latest version of PHP and cURL set up properly, as far as I know so there shouldn't be any problem at that end. I'd prefer JavaScript to retrieve products but I'm open minded.
I happen to not be highly skilled, but I'd like to get my foot in the door.
edit: I will show you the code that doesn't work, and the error it is giving me.
<?php
// Your developer key
$cj_id = "My ID - omitted for privacy.";
// Your website ID
$website_id = "Also removed for privacy.";
// Keywords to search for
$keywords = "credit+card";
// URL to query with cURL
$url = "https://product-search.api.cj.com/v2/product-search?website-id=$website_id&keywords=$keywords";
// Initiate the cURL fetch
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
// Send authorization header with the CJ ID. Without this, the query won't work
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: '.$cj_id));
$result = curl_exec($ch);
// Put the results to an object
$resultXML = simplexml_load_string($result);
// Print the results
print "<pre>";
print_r($resultXML);
print "</pre>";
?>
Now, this is the error that it's giving me.
SimpleXMLElement Object
(
[error-message] => Invalid Key provided. Valid keys are: advertiser-ids, advertiser-sku, currency, high-price, high-sale-price, isbn, keywords, low-price, low-sale-price, manufacturer-name, manufacturer-sku, page-number, records-per-page, serviceable-area, sort-by, sort-order, upc, website-id
)
You have a error in your URL, try this:
$url = "https://product-search.api.cj.com/v2/product-search?website-id=$website_id&keywords=$keywords";
instead of :
$url = "https://product-search.api.cj.com/v2/product-search?website-id=$website_id&keywords=$keywords";
<?php
echo '<pre>';
$url='https://product-search.api.cj.com/v2/product-search?website-id=your-id-key-here&advertiser-ids=4415206&records-per-page=999&serviceable-area=US';
$CJ_KEY='0085eb59c8928f028ba5b27bccfe17cdd20cf4e9079b977b2cc6df72752abab9205676a2f7ee67befe9dccab85f656ef46aba49e500faccbf75dfc6e03f655334d/00848a3f9bf0e13525bce27f008d6245c3e42ae80f2d80a8d9d2220807ca386f4b10146cbbcfff06aafb5e49c03a3318213389dee7861abb2dd7229470390a89c9';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, FAlSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: '.$CJ_KEY));
$curl_results = curl_exec($ch);
$xml = simplexml_load_string($curl_results);
var_dump($xml);
// Loop Insert Product to database
echo '<pre>';
// if you no set: records-per-page=999, default get 50 products latest
// advertiser-ids=4415206 is Id of Advertiser in CJ, you can replace other id ,
Hope helpful for you , good luck !
?>
Hi I am trying to get the count for all nodes with certain content or value. In this case I have an xml as so:
<hotel>
<city>Cancun</city>
<postalCode>77500</postalCode>
<countryCode>MX</countryCode>
<airportCode>CUN</airportCode>
<supplierType>E</supplierType>
<propertyCategory>1</propertyCategory>
<hotelRating>4.0</hotelRating>
<confidenceRating>52</confidenceRating>
</hotel>
I need to find all hotelRating with the value of 4 and count how many there are in my xml list. I have no idea of how to do this with php. If anyone can help me with this I would appreciate it so much!!
By the way I have already connected the xml file as follows and am able to get data and send data.
$post_string= 'type=xml&cid=222&minorRev=14&apiKey=222&locale='.$userLocale.'¤cyCode='.$userCurr.'&customerIpAddress='.$userIp.'&customerUserAgent='.$userAgent.'&xml=<HotelListRequest><destinationId>'.$destinationId.'</destinationId><arrivalDate>'.$arriving.'</arrivalDate><departureDate>'.$departing.'</departureDate><RoomGroup>'.$xmlQuery.'</RoomGroup><supplierCacheTolerance>MED_ENHANCED</supplierCacheTolerance></HotelListRequest> ';
//Relative path to the file with $_POST parsing
$path = "http://api.ean.com/ean-services/rs/hotel/v3/list";
$ch = curl_init($path);
$fp = fopen('xml/data.xml','w');
//Send the data to the file
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
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('xml/data.xml');
}
Thank you in advance for any help!!!
foreach ($data->hotel as $hotel)
{
if ($hotel->hotelRating == '4.0')
{
// hotel with 4.0 rating found
}
}
$count = $data->xpath("count(\"//hotel[hotelRating= '4.0']\")");
Will give you the count of hotels where hotelrating = 4.0.
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¤cyCode=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;
}
}