Hello I am getting xml feed from expedia and trying to parse it onto the screen. It is not returning the data, and I can not figure out why. the only thing that will return is activePropertyCount. Here is the url where I am doing this if you want to take a look: http://travellinginmexico.com/test/index.php and here is the xml that I am trying to parse: http://travellinginmexico.com/test/data.xml
My code:
<?php
$post_string = 'type=xml&cid=55505&minorRev=5&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('data.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('data.xml');
echo "<ul id=\"data\">\n";
foreach ($data as $info):
$title=$info->HotelList;
$add=$info->address1;
$count=$info['activePropertyCount'];
echo "<li><div class=\"title\">",$title,"</div><div class=\"artist\">by ",$add,"</div><time>",$count,"</time></li>\n";
endforeach;
echo "</ul>";
?>
It appears that you are not trying to retrieve your data from the correct part of the XML object. I have updated your code to read from the HotelList->HotelSummary section, and it will now display the hotel name and address properly.
//Use Curl to get XML here.
$data = simplexml_load_file('data.xml');
//Uncomment this to view the parsed XML on screen.
/*
echo '<pre>';
print_r($data->HotelList);
echo '</pre>';
*/
echo "<ul id=\"data\">\n";
foreach($data->HotelList->HotelSummary as $info):
$title=$info->name;
$add=$info->address1;
$count=$data->HotelList['activePropertyCount'];
echo "<li><div class=\"title\">",$title,"</div><div class=\"artist\">by ",$add,"</div><time>",$count,"</time></li>\n";
endforeach;
echo "</ul>";
I recommend checking out libxml_get_errors. There's a fairly good example on how to use it in the PHP documentation for the function. It should be able to tell you what problems are occurring during simplexml_load_file.
If you think the problem is coming from cURL (or to be a little more thorough) you can use the cURL error functions as well. (Such as curl_error).
Related
I am trying to senddata to a url by using curl with codeigniter. I have successfully implemented the code for sending the data as below.
function postToURL($reg_no, $data)
{
$url = 'http://localhost/abcSystem/Web_data/viewPage';
$send_array = array(
'reg_no' =>$reg_no,
'data' =>$data,
);
$fields_string = http_build_query($send_array);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 600);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_REFERER, $url);
$post_data = 'json='.urlencode(json_encode($send_array));
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$output = curl_exec($ch);
if (curl_errno($ch)) {
die('Couldn\'t send request: ' . curl_error($ch));
} else {
$resultStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($resultStatus == 200) {
print_r('success'); // this is outputting
return $output;
} else {
die('Request failed: HTTP status code: ' . $resultStatus);
}
}
curl_close($ch);
}
The out put is success. I want to see if this post data can be retrieved. So I tried to change the above url controller file as below.
$fp = fopen('php://input', 'r');
$rawData = stream_get_contents($fp);
echo "<pre>";
print_r($rawData);
echo "</pre>";
But nothing is printing. I want to get the data of posting. Please help me on this.
Your Written code
$fp = fopen('php://input', 'r');
$rawData = stream_get_contents($fp);
echo "<pre>";
print_r($rawData);
echo "</pre>";
is not to Print or capture Posted Data . Because you are dealing with Current Page PHP INPUT Streaming , whereas you are posting data on Other URL . So what you need to do is just Put a log of posted data in File. Use below code after $output = curl_exec($ch)
file_put_contents("posted_data.txt", $post_data );
This way you will be able to write your each post in file Posted_data.txt File - Make sure you give proper File Permission. If you want to keep trace of each POST than just make the file name dynamic so per API Call it can write a log.
Another option is to save the $post_data in DATABASE - Which is not suggestable from Security point of view.
Where ever you are calling your postToURL() function, you need to output the result of it.
For example:
$output = postToURL('Example', array());
echo $output;
This is because you are returning the curl output rather outputting it.
I have this really long JSON string: http://pastebin.com/2jJKSGHs , which is being pulled from a music API.
I have this code set up to parse it ( http://pastebin.com/EuJtuhHg ):
$url = "https://api.discogs.com/database/search?type=artist&q=pink[keyandsecretredacted]";
//initialize the session
$ch = curl_init();
//Set the User-Agent Identifier
curl_setopt($ch, CURLOPT_USERAGENT, 'YourSite/0.1 +http://your-site-here.com');
//Set the URL of the page or file to download.
curl_setopt($ch, CURLOPT_URL, $url);
//Ask cURL to return the contents in a variable instead of simply echoing them
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//Execute the curl session
$output = curl_exec($ch);
//close the session
curl_close ($ch);
//decode and print output
$output = json_decode($output2, true);
echo($output['results'][0]['title']);
When I insert the contents of the JSON string directly into my code, the json_decode works perfectly on it. But when I try to grab it from the API using the method above, nothing prints on my page -- it's just empty. Printing out json_last_error returns "0", so it's not detecting any errors.
Any ideas why this might be happening?
Replace
$output = curl_exec($ch);
with
$output2 = curl_exec($ch);
Otherwise $output2 isn't defined, and json_decode is using an undefined variable:
$output = json_decode($output2, true);
I am use curl method to get response from server.
but when ehco this response it show as simple data.
but in view source it show xml format.
can anybody tell me how to print response as xml
I am using this code:
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
//curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $post_data_tcetra);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
Use this:
ob_start();
$result = curl_exec($ch);
$xml = ob_get_contents();
ob_end_clean();
echo htmlspecialchars($xml);
The actual function you're searching for is called htmlspecialchars(). It converts symbols like < to to their entity references <.
In my code above, we also need the Output Caching (ob_*) functions, so that we can prevent the output from directly being sent to the browser. I'd suggest you though that you use the better way in the code below:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
if ($result === false) {
// error handling
}
else {
echo htmlspecialchars($result);
}
I have an XML file I need to pass.
http://mckay.canvashost.com:8080/opentripplanner-api-webapp/ws/transit/stopTimesForStop?id=27833&startTime=1361784386000&extended=true&references=true
I used PHP's CURL to load it into the page:
$url = "http://mckay.canvashost.com:8080/opentripplanner-api-webapp/ws/transit/stopTimesForStop?id=27833&startTime=1361784386000&extended=true&references=true";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
$xml = curl_exec($ch);
curl_close($ch);
echo htmlentities($xml, ENT_QUOTES, "UTF-8");
The output is a JSON file, which I wasn't expecting. No matter, I continued working with the JSON but can't seem to parse it.
I had thought this would work:
$obj=json_decode($xml);
echo $obj[stopTime][0][phase];
With a result of 'departure'. I've spent a good while on this yet can't get it to output anything.
Anyone help? And anyone know at which point it switched from an XML file to JSON format?
the output is a xml-string.
try to use php's xml functionality delivered by SimpleXml:
SimpleXml
as soon as you successfully parsed the string you can iterate its nodes like an array
foreach ($xmlElement as $node) {
echo $node->attributeName;
}
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.