how to convert HTML data to json, example as below, description content how to convert as json, it is from mysql, php., how to send json responce as plain text, but description comes from the mysql db as it is, but how to send the json responce api to androind.
public function actionTestanalysis()
{
//echo $keyword=$_POST['keyword'];
$query= Yii::app()->db->createCommand("select * from test ORDER BY id DESC")->queryAll();
$arr = array();
if(count($query) > 0) {
foreach($query as $query){
$arr[] = $query;
}
}
# JSON-encode the response
$json_response = json_encode($arr);
// # Return the response
echo $json_response;
//exit;
}
json responce
[
{
"id": "99",
"name": "Max-Gain on or before 25th January 2016 in Max India Limited.",
"description": "
\r\n\tMax India Limited has announced the Record date for Three way De-Merger as 28th January 2016 (Thursday). <\/div>\r\n
\r\n\t <\/div>\r\n
\r\n\tAnyone want to Gain from the three way De-Merger of Max India Group one should buy the shares of Max India Limited on or before – 25th January 2016 (Cum-Date – Monday Tentavily) otherwise to be on safer side you can buy on or before 22nd January 2016(Friday) and get invested in it.<\/div>\r\n
\r\n\t <\/div>\r\n
\r\n\tIf any investor invests for a period Of 12 – 18 Months , this scrip will be a Multifold - Multi Bagger.<\/div>\r\n
\r\n\t <\/div>\r\n
\r\n\tTo View the full report on Max India Limited authored . <\/div>\r\n
\r\n\t <\/div>\r\n
\r\n\tPlease Click The Below Link<\/div>\r\n
\r\n\t
\r\n\t\thttp:\/\/www.test.com\/index.php\/newsOpportunities\/list\/scroll\/no-pain-all-gain-maximum-benefit-in-max-india-ltd<\/a><\/p>\r\n<\/div>\r\n",
"image": "",
"status": "unlock"
},
You have also one error in the cycle in your code.
Try this:
if (count($query) > 0) {
foreach ($query as $queryElement) {
$el = $queryElement;
$el['description'] = trim(preg_replace('/\s+/', ' ', strip_tags($el['description'])));
$arr[] = $el;
}
}
Try before: echo $json_response set header content type to application/json
<?PHP
header('Content-Type: application/json');
echo $json_response;
Use htmlentities() instead of strip_tags(), in order to retain actual content stored in db.
Related
How would I decode this JSON data to get the Location link of the event? NOTE: When I say Location I don't mean the field "location" in the json data, I am referring to the field which is in "customFields", then has a "value" which is a link to Google Maps, it also has the "type" = 9.
Problem: I am currently stuck with a page which looks like the image below, the "Notice: Undefined offset: # in...." error continues for 200 lines, because the JSON file contains the data of 200 events, the JSON included only contains the first event.
Desired Result: For the link to google maps page to be echoed on every line. I think the solution is very simple, just changing my Source code (Included) so that it can read the JSON file.
JSON dataset:
[{"eventID":152913573,"template":"Brisbane City Council","title":"Clock Tower Tour","description":"The Clock Tour Tower is a ‘must-do’ for anyone and everyone in Brisbane!<br /> <br /> For many years, City Hall’s Clock Tower made the building the tallest in Brisbane, offering visitors a magnificent 360 degree view of the city around them. Whilst the view has changed significantly over the last 90 years, the time-honoured tradition of “taking a trip up the tower” happily continues at Museum of Brisbane.<br /> <br /> The Clock Tower Tour includes a ride in one of Brisbane’s oldest working cage lifts, a look behind Australia’s largest analogue clock faces and time to explore the observation platform that shares a unique perspective of the city. See if you can catch a glimpse of the bells!<br /> <br /> <strong>Location</strong>: Tour begins from Museum of Brisbane reception on Level 3 of City Hall.","location":"Museum of Brisbane, Brisbane City","webLink":"","startDateTime":"2021-06-13T00:00:00","endDateTime":"2021-06-14T00:00:00","dateTimeFormatted":"Sunday, June 13, 2021","allDay":true,"startTimeZoneOffset":"+1000","endTimeZoneOffset":"+1000","canceled":false,"openSignUp":false,"reservationFull":false,"pastDeadline":false,"requiresPayment":false,"refundsAllowed":false,"waitingListAvailable":false,"signUpUrl":"https://eventactions.com/eareg.aspx?ea=Rsvp&invite=0tva7etjn38te1bve2yj59425pupt7wvscmr1z6depcj9ctnrh7r","repeatingRegistration":0,"repeats":"Every Sunday, Tuesday, Wednesday, Thursday, Friday and Saturday through June 30, 2021","seriesID":152913560,"eventImage":{"url":"https://www.trumba.com/i/DgDhxtvzZEBEz%2AjAEUDofPUE.jpeg","size":{"width":1290,"height":775}},"detailImage":{"url":"https://www.trumba.com/i/DgDhxtvzZEBEz%2AjAEUDofPUE.jpeg","size":{"width":1290,"height":775}},"customFields":[{"fieldID":22503,"label":"Venue","value":"Museum of Brisbane, Brisbane City","type":17},{"fieldID":22505,"label":"Venue address","value":"Museum of Brisbane, Brisbane City Hall, 64 Adelaide Street, Brisbane City","type":9},{"fieldID":21859,"label":"Event type","value":"Family events, Free","type":17},{"fieldID":22177,"label":"Cost","value":"Free","type":0},{"fieldID":23562,"label":"Age","value":"Suitable for all ages","type":0},{"fieldID":22732,"label":"Bookings","value":"Book via the Museum of Brisbane website.","type":1},{"fieldID":51540,"label":"Bookings required","value":"Yes","type":3}],"permaLinkUrl":"https://www.brisbane.qld.gov.au/trumba?trumbaEmbed=view%3devent%26eventid%3d152913573","eventActionUrl":"https://eventactions.com/eventactions/brisbane-city-council#/actions/cvuzsak1g2d45mndcjwkp24nfw","categoryCalendar":"Brisbane's calendar|Museum of Brisbane","registrationTransferTargetCount":0,"regAllowChanges":true}]
Code so far:
<?php
$output = file_get_contents("Events.json");
$decode = json_decode($output, true);
for($i = 0; $i < count($decode); $i++) {
if($decode[$i]['customFields'][$i]['type'] == 9){
echo $decode[$i]['customFields'][$i]['label'][$i]['value'];
}
echo "<br>";
}
?>
You're using the $i loop counter twice in the same expression, but the second time you use it it's pointing at non-existent elements. The snippet below 1) treats JSON objects as objects (I find it less confusing when matching code to data), and 2) uses foreach to iterate over the arrays.
I've also extracted the latitude and longitude for you into $latlong
Try this:
$decode = json_decode($json);
foreach ($decode as $event) {
foreach ($event->customFields as $field) {
if ($field->type == 9) {
echo $field->value."\n";
if (preg_match('/href="(.*?)"/', $field->value, $matches)){
preg_match('/q=([\-\.0-9]*),([\-\.0-9]*)/',$matches[1], $latlong);
array_shift($latlong);
var_dump($latlong);
}
break;
}
}
}
Output
Museum of Brisbane, Brisbane City Hall, 64 Adelaide Street, Brisbane City
array(2) {
[0]=>
string(11) "-27.4693454"
[1]=>
string(11) "153.0216909"
}
Demo:https://3v4l.org/AkRvI
I've got a project that involves getting flight information from a database.
I want the results to look like:
01 Nov 2017 - Eastern Airways 7601
Departing from Southampton, Eastleigh (SOU) at 0840
However my code seems to bring up the below with a mysterious live of nonsense as per below
01 Nov 2017 - Eastern Airways 7601
Departing from , () at 084001 Nov 2017 - 7601 //this line I don't want
Departing from Southampton, Eastleigh (SOU) at 0840
$link = mysqli_connect('xxx', 'xxx', 'xxx', 'xxx' );
foreach ($flights as $b) {
$query = "SELECT * FROM `airlines` WHERE `iatacode` = '$airline' LIMIT 0 , 30;";
$query .= "SELECT * FROM `airports` WHERE `Airport Code` = '$depdest' LIMIT 0 , 30;";
/* Execute queries */
if (mysqli_multi_query($link, $query)) {
do {
/* store first result set */
if ($result = mysqli_store_result($link)) {
while ($row = mysqli_fetch_array($result))
/* print results */
{
$date=date_create($depdate);
echo "<b>" . date_format($date,"d M Y"). " - ". $row['airlinename']." ".$flightno. "</b><br/>";
echo "Departing from " .$row['City Name'].", ".$row['Airport Name']." (".$row['Airport Code'].") at " . $deptime;
}
mysqli_free_result($result);
}
} while (mysqli_next_result($link));
}
Can anyone see what I'm doing wrong?
Data base tables are as below
table 1 - Name "airports"
Airport ID City name Airport Code Airport Name Country name Country Abbrev. World Area Code
1, 108 Mile Ranch, ZMH , 108 Mile Ranch , Canada, CA, 906,
2, Aachen, AAH Aachen/Merzbruck, Germany, DE, 429,
3, Aachen, ZIU, Railway, Germany, DE, 429,
4, Aalborg, AAL, Aalborg, Denmark, DK, 419,
etc
table 2 - Name "airlines"
airline id, Iata, Airline Name
1, 0A, Amber Air,
2, 0B, Blue Air,
3, 0C, IBL Aviation,
etc
Thanks!
If I was to guess, I would say that there is a problem with the $b variable.
It seems your output is being written twice: the value "084001" in the middle of the second line looks to be the 0840 flight time from one entry, and then immediately starting the next entry as the date.
I would guess that the foreach is looping twice, instead of once, causing two outputs.
Could you do an output of the $b variable?
echo "<pre>";
print_r($b);
echo "</pre>";
So I have an API from a Payment gateway which return all the transaction in a day which is in Json format something like this.
{
"status":"1",
"msg":"3 transactions settled on 2016-09-29",
"Txn_details":[
{
"payuid":"58800xxxxxx",
"txnid":"xxxxxx-27410",
"txndate":"2016-09-27 11:06:58",
"mode":"DC",
"amount":"15174.51",
"requestid":"xxxxxxxx",
"requestdate":"2016-09-29 18:17:18",
"requestaction":"capture",
"requestamount":"15174.51",
"mer_utr":"xxxxxxx",
"mer_service_fee":"151.75000",
"mer_service_tax":"22.76000",
"mer_net_amount":"15000.00000",
"bank_name":"VISA",
"issuing_bank":"xxxxxx",
"merchant_subvention_amount":"0.00"
},
{
"payuid":"58800xxxxxx",
"txnid":"xxxxxx-27410",
"txndate":"2016-09-27 11:06:58",
"mode":"DC",
"amount":"15174.51",
"requestid":"xxxxxxxx",
"requestdate":"2016-09-29 18:17:18",
"requestaction":"capture",
"requestamount":"15174.51",
"mer_utr":"xxxxxxx",
"mer_service_fee":"151.75000",
"mer_service_tax":"22.76000",
"mer_net_amount":"15000.00000",
"bank_name":"VISA",
"issuing_bank":"xxxxxx",
"merchant_subvention_amount":"0.00"
}
]
}
So In this Json I have to look for a value called requestid so I have to look for that id by calling the API from the day of payment to next 7 days
and match every record of each day weather it has the requestid . My code is like this
function recursiveUTNRcheck($date_of_payment,$payment_reference,$rec_counter=7){
$date = substr($date_of_payment, 0, 10);
$utrNos ='';$brtoggle=false;
for($i=1;$i<=$rec_counter;$i++){
$sett_date= date('Y-m-d', strtotime($date. ' + '.$i.' days'));
$responsePayu = $this->callPayU($sett_date);
$utrnos=array('status'=>0);
if(!is_null($responsePayu)){
$utrNos = json_decode($responsePayu,true);
foreach ($utrNos['Txn_details'] as $value) {
# code...
if($value['requestid']==$payment_reference){
$utrnos['status']=1;
$utrnos['data'] = $value;
$brtoggle=true;
break;
}
}
if($brtoggle)
break;
}
}
return $utrnos;
}
My problem is if suppose there is like 2000 payment in a day , then the for loop will have to fun for 2000 times and it has to do keep doing it for everyday until it gets it id ,
Worst case could be 7*2000 = 14000 times .
So I was thinking can there be a better way to match the string requestid directly into the json string ? so I think the performance might be bit better than decoding and checking the array.
Thanks
I am trying to display coordinates from Twitter Search API 1.1 (GET).
I can output the entire JSON file after encoding the tweets - http://pastebin.com/bKLye2an
$search = str_replace("#", "%23", $search);
$tweets = $connection->get("https://api.twitter.com/1.1/search/tweets.json?q=".$search."&count=".$notweets);
$json = json_encode($tweets);
However, in PHP I used the following codes to display the coordinates and nothing appears.
foreach ($json['statuses'] as $key => $value)
{
foreach ($json['coordinates']['coordinates'] as $key => $value)
{
echo "$key: $value\n";
};
};
As far as I can see, the structure is statuses-coordinates-coordinates for geo.
How do I echo coordinates (if present) for all tweets in search).
Given your sample json string, a simple foreach is enough. Consider this example:
$json_string = '{"statuses":[{"metadata":{"result_type":"recent","iso_language_code":"en"},"created_at":"Mon Jun 16 08:35:18 +0000 2014","id":478455763761786880,"id_str":"478455763761786880","text":"Later go shop at cold storage. LOLOL","source":"Twitter for Android<\/a>","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":559622523,"id_str":"559622523","name":"AhYong","screen_name":"likeasomebodeh","location":"To each and every road.","description":"Fun-Sized \/ CE1404N \/ BARVENGERS \/ Sagittarian \/ Sixth Gun \/ Drummer - Wannabe","url":"http:\/\/t.co\/PFSXy17655","entities":{"url":{"urls":[{"url":"http:\/\/t.co\/PFSXy17655","expanded_url":"http:\/\/ask.fm\/Ah_Yong","display_url":"ask.fm\/Ah_Yong","indices":[0,22]}]},"description":{"urls":[]}},"protected":false,"followers_count":329,"friends_count":444,"listed_count":1,"created_at":"Sat Apr 21 13:30:49 +0000 2012","favourites_count":4930,"utc_offset":28800,"time_zone":"Beijing","geo_enabled":false,"verified":false,"statuses_count":33116,"lang":"en","contributors_enabled":false,"is_translator":false,"is_translation_enabled":false,"profile_background_color":"131516","profile_background_image_url":"http:\/\/abs.twimg.com\/images\/themes\/theme14\/bg.gif","profile_background_image_url_https":"https:\/\/abs.twimg.com\/images\/themes\/theme14\/bg.gif","profile_background_tile":true,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/459318345003593728\/mhjxKipm_normal.jpeg","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/459318345003593728\/mhjxKipm_normal.jpeg","profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/559622523\/1401358655","profile_link_color":"009999","profile_sidebar_border_color":"EEEEEE","profile_sidebar_fill_color":"EFEFEF","profile_text_color":"333333","profile_use_background_image":true,"default_profile":false,"default_profile_image":false,"following":false,"follow_request_sent":false,"notifications":false},"geo":null,"coordinates":null,"place":null,"contributors":null,"retweet_count":0,"favorite_count":0,"entities":{"hashtags":[],"symbols":[],"urls":[],"user_mentions":[]},"favorited":false,"retweeted":false,"lang":"en"}],"search_metadata":{"completed_in":0.016,"max_id":478455763761786880,"max_id_str":"478455763761786880","next_results":"?max_id=478455763761786879&q=flu%20OR%20cold%20OR%20%23flu%20OR%20%23cold%20OR%20%23snot%20OR%20%23ill&count=1&include_entities=1","query":"flu+OR+cold+OR+%23flu+OR+%23cold+OR+%23snot+OR+%23ill","refresh_url":"?since_id=478455763761786880&q=flu%20OR%20cold%20OR%20%23flu%20OR%20%23cold%20OR%20%23snot%20OR%20%23ill&include_entities=1","count":1,"since_id":0,"since_id_str":"0"}}';
$json = json_decode($json_string, true);
foreach($json['statuses'] as $key => $json_values) {
if(isset($json_values['coordinates']) && !empty($json_values['coordinates'])) {
// continue your processes if key exists and not empty
}
}
Important Note: In your given json, take note, your coordinates is null
I'm working with an API from underground weather. I'm trying to put some values into my website on localhost. I include a lot of values without problem. Like:
Temperature: 30°F
Wind: Fast
Here is the json of those values:
"current_observation": {
"image": {
"url":"http://icons-ak.wxug.com/graphics/wu2/logo_130x80.png",
"title":"Weather Underground",
"link":"http://www.wunderground.com"
},
"display_location": {
"full":"Buenos Aires, Argentina",
"city":"Buenos Aires",
"state":"",
"state_name":"Argentina",
"country":"AG",
"country_iso3166":"AR",
"zip":"00000",
"magic":"1",
"wmo":"87582",
"latitude":"-34.56999969",
"longitude":"-58.41999817",
"elevation":"6.00000000"
},
"observation_location": {
"full":"Palermo, Buenos Aires, Ciudad Autónoma de Buenos Aires",
"city":"Palermo, Buenos Aires",
"state":"Ciudad Autónoma de Buenos Aires",
"country":"Argentina",
"country_iso3166":"AR",
"latitude":"-34.595318",
"longitude":"-58.419781",
"elevation":"124 ft"
},
"estimated": {
},
"station_id":"IBUENOSA157",
"observation_time":"Last Updated on April 26, 7:52 PM ART",
"observation_time_rfc822":"Sat, 26 Apr 2014 19:52:51 -0300",
"observation_epoch":"1398552771",
"local_time_rfc822":"Sat, 26 Apr 2014 19:52:52 -0300",
"local_epoch":"1398552772",
"local_tz_short":"ART",
"local_tz_long":"America/Buenos_Aires",
"local_tz_offset":"-0300",
"weather":"Clear",
"temperature_string":"65.8 F (18.8 C)",
"temp_f":65.8,
"temp_c":18.8,
"relative_humidity":"63%",
and in the index php file:
<?php
$json_string = file_get_contents("http://api.wunderground.com/api/f84c5a4cd54b3216/geolookup/alerts/astronomy/almanac/conditions/forecast/hourly/q/autoip.json");
$parsed_json = json_decode($json_string);
$temp_c = $parsed_json->{'current_observation'}->{'temp_c'};
echo "{$'temp_c'};
That displays the temperature. The temperature in the json code is in: Current_observation and then the value temp_c.
The problem is that I want to echo the forecast, and the forecast is in a different location than the temp_c.
For example. I want to echo the current conditions, that is here:
The problem is, that is in:
{'forecast'}->{'simpleforecast'}->{'forecastday'} and then there is a zero for the current day, a 1 for the next day, a 2 for the following day, and a 3 for the next to the next day.
When I try to do that in php:
{'forecast'}->{'simpleforecast'}->{'forecastday'}->{'0'}->{'conditions'};
It does not show anything. How I can go into a value json when in the array there is a 0?
PD: for 0, there is one condition, for 1 (that is next day) there is other condition, and like that the others day. Thanks
For me it just works fine, I just tested your code, I just modified it a little bit:
<?php
$json_string = file_get_contents("http://api.wunderground.com/api/f84c5a4cd54b3216/geolookup/alerts/astronomy/almanac/conditions/forecast/hourly/q/autoip.json");
$parsed_json = json_decode($json_string, true);
$desired_forecast = $parsed_json['forecast']['simpleforecast']['forecastday'][0]['conditions'];
echo '<pre>';
print_r($desired_forecast); // Thunderstorm
echo '</pre>';
It is accessible.
You were really close but {'0'} means there is an object with the key 0, while you really wanted to access the first index of forecastday
var_dump($parsed_json->{'forecast'}->{'simpleforecast'}->{'forecastday'}[0]->conditions);