Parsing a JSON string (or is it XML?) - php

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;
}

Related

return Json string not working

I want to get data from api..
but I have trouble with json ..I can not get json string .. it print as normal string or xml..
I try multi method from net but no solution..
this my code:
$url = "http://fv4online.com/egov_api/v1/students/7";
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER,array('Accept:
application/json;charset=UTF-8'));
// set url
curl_setopt($ch, CURLOPT_URL, $url);
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
print_r($output);
$t=json_decode($output,true);
print_r($t);
// close curl resource to free up system resources
curl_close($ch);
result of print ($output) is string:
7345345343testtesttesttest2000testliterary4564620171testDamascusar_lang300600350en_lang160400200fr_lang160400200national80200100history120300200geograph120300200philosophy160400300religion802001501700155060successful
and result of print(var_dump($output)) is xml:
'
7345345343testtesttesttest2000testliterary4564620171testDamascusar_lang<'... (length=1544)
note: Previously I was able to get this data without any problems, but suddenly the problem arose
That string contains all values the XML from the url returns, just without the tags around them. If you do 'View Source' you'll see more.
You get XML, not JSON. Could be they've changed that (which would be a bit odd, but I've seen worse). If you want is as JSON:
$xml = simplexml_load_string($xml_string);
$json = json_encode($xml);

JSON text unparseable when using cURL to grab 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);

curl_exec() outputting destination contents to page?

I'm using the following code:
$ch = curl_init('www.google.com');
$output = curl_exec($ch);
curl_close($ch);
This is not the first time I've used cURL, and unless I'm mistaken the above code should retrieve the contents of google.com and store it in $output. Correct?
So, why then, does the above code output the contents (in this example the Google homepage) to the page? I'm not echo'ing anything out, but for some reason the curl_exec() function is outputting what it returns to the page.
Am I missing something?
you need to use
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
That will tell curl_exec not to output the results
so change it all to
$ch = curl_init('www.google.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);

Php not reading xml data

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&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('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).

Help w/ Retrieving XML via cURL

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&currencyCode=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&currencyCode=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!!!

Categories