Stargate22 Posted September 22, 2015 Share Posted September 22, 2015 (edited) Hello guys, I have a ajax connection to my json.php file and its not working... do you have any idea what is going on? is it my $output variable is it not convertible to json can it be my ajax?! any help will be greatly appreciated. <?php #$KEY if(isset($_POST['city'])){ $city = $_POST['city']; //checks if variable city is set if not it will be set as default to bcharest #var_dump($city); }else{ $city = 'New York'; } //loads data as simple xml $result = "http://api.wunderground.com/api/KEY/geolookup/conditions/q/us/$city.xml"; $xml = simplexml_load_file($result); #echo htmlspecialchars($result, ENT_QUOTES, 'UTF-8'); $place = $xml->location->city; //gets the city name #ar_dump($place); if(!empty($place)){ //checks if city exits foreach($xml->current_observation as $item){ $current = $item->xpath('weather'); $temperature = $item->xpath('temp_c'); $time = $item->xpath('local_time_rfc822'); // parsing the document in order to get the needed info $wind = $item->xpath('wind_string'); #$wind = array_map( 'strtolower' ,$wind); $humidity = $item->xpath('relative_humidity'); $output = array($time[0], $temperature[0], $current[0],$wind[0],); } }else{ $output = '<h1>No results found, please try a different city.</h1>'; //if variable $place is empty it will print this } header('Content-Type: application/json'); json_encode($output[0]); echo $output[0]; ?> and my ajax: $(document).ready(function() { $('li').click(function(){ var city = $(this).text(); //get the li content as variable city $.ajax({ type : 'POST', //sending data method url : 'json.php', data : {city:city}, //data to be sent dataType: 'json', success : function(data){ $("#result").html(data[0]); } }); }); }); Edited September 22, 2015 by requinix removing api key Quote Link to comment https://forums.phpfreaks.com/topic/298274-php-array-to-json_encode-not-working/ Share on other sites More sharing options...
requinix Posted September 22, 2015 Share Posted September 22, 2015 Do not post sensitive things like API keys to a public forum. I've removed it for you this one time as a courtesy so be more careful in the future. 1. I don't know what XML you're looking at, but the one I'm looking at doesn't have things like location/city or current_observation. 2. You must do some work with $city before you stick it in the URL. Do some simple validation and then use rawurlencode() when putting it in the URL. 3. You are using a loop for the current_observation. If there is more than one then your $output will be messed up because you keep overwriting it each time through the loop. 4. json_encode() does not output anything. You have to echo the return value yourself. 5. $output[0] is just the time. Or the first character in the error message. 6. Outputting $output[0] will (likely) not be valid JSON. Use json_encode(), output the return value, and don't output anything else. 7. That HTML string is not valid JSON. Figure out another way to show an error message. Quote Link to comment https://forums.phpfreaks.com/topic/298274-php-array-to-json_encode-not-working/#findComment-1521364 Share on other sites More sharing options...
Stargate22 Posted September 22, 2015 Author Share Posted September 22, 2015 (edited) @requinix Do not post sensitive things like API keys to a public forum. I've removed it for you this one time as a courtesy so be more careful in the future.1. I don't know what XML you're looking at, but the one I'm looking at doesn't have things like location/city or current_observation.2. You must do some work with $city before you stick it in the URL. Do some simple validation and then use rawurlencode() when putting it in the URL.3. You are using a loop for the current_observation. If there is more than one then your $output will be messed up because you keep overwriting it each time through the loop.4. json_encode() does not output anything. You have to echo the return value yourself.5. $output[0] is just the time. Or the first character in the error message.6. Outputting $output[0] will (likely) not be valid JSON. Use json_encode(), output the return value, and don't output anything else.7. That <h1> HTML string is not valid JSON. Figure out another way to show an error message. Thank you for removing the key and for the help! 1. xml is attached (there is location and curent_observation. 2.3. my loop is working.. if i replace the $output and skip the json_encode().. it is working perfectly script is activated when user click on a <li> element from my index. 5.6 Updated my last bit of code and it is printing when i click on a city that does not exist.. but when i click one that does.. it does not print anything.. header('Content-Type: application/json'); echo json_encode($output); ?> 7. removed the <h1> and its working perfectly I think the problem is here... this output does not get printed ...and also no error.. is this line not correct? $output = array($time[0], $temperature[0], $current[0],$wind[0],); Thank you very much for your support! Edited September 22, 2015 by Stargate22 Quote Link to comment https://forums.phpfreaks.com/topic/298274-php-array-to-json_encode-not-working/#findComment-1521365 Share on other sites More sharing options...
Ch0cu3r Posted September 23, 2015 Share Posted September 23, 2015 I think the problem is here... this output does not get printed ...and also no error.. is this line not correct? $output = array($time[0], $temperature[0], $current[0],$wind[0],);Thank you very much for your support! How are you testing/viewing the output of your script? With that line of code see point 3 3. You are using a loop for the current_observation. If there is more than one then your $output will be messed up because you keep overwriting it each time through the loop. As there is are multiple observation values then you should be assigning the array with the observation data to $output[] $output[] = array($time[0], $temperature[0], $current[0],$wind[0],); otherwise you are just overwriting previous observation values with the next observation values.This will result in only the last observation values being stored in $output rather than all the observation values. Quote Link to comment https://forums.phpfreaks.com/topic/298274-php-array-to-json_encode-not-working/#findComment-1521397 Share on other sites More sharing options...
QuickOldCar Posted September 23, 2015 Share Posted September 23, 2015 I find it easier to build the array and check it, once the data is as expected, then send as json and just send the main array. $output = array(); //in a loop adding to the array $output[] = array($time[0], $temperature[0], $current[0],$wind[0],); or assigning key values $output[] = array("time"=>$time[0], "temperature"=>$temperature[0], "current"=>$current[0],"wind"=>$wind[0],); does it look right? var_dump($output); or echo "<pre>"; print_r($output); echo "<pre>"; If that array is good then echo it out, and comment out anything that echoes prior. As Ch0cu3r mentioned do not add html, sending json is just for data and not style. Do that if need to optionally when getting the request for display. header('Content-Type: application/json; charset=utf-8'); echo json_encode(array('data' => $output),true); Quote Link to comment https://forums.phpfreaks.com/topic/298274-php-array-to-json_encode-not-working/#findComment-1521409 Share on other sites More sharing options...
QuickOldCar Posted September 23, 2015 Share Posted September 23, 2015 Noticed an extra comma here $output[] = array($time[0], $temperature[0], $current[0],$wind[0],); Quote Link to comment https://forums.phpfreaks.com/topic/298274-php-array-to-json_encode-not-working/#findComment-1521410 Share on other sites More sharing options...
Stargate22 Posted September 23, 2015 Author Share Posted September 23, 2015 I find it easier to build the array and check it, once the data is as expected, then send as json and just send the main array. $output = array(); //in a loop adding to the array $output[] = array($time[0], $temperature[0], $current[0],$wind[0],); or assigning key values $output[] = array("time"=>$time[0], "temperature"=>$temperature[0], "current"=>$current[0],"wind"=>$wind[0],); does it look right? var_dump($output); or echo "<pre>"; print_r($output); echo "<pre>"; If that array is good then echo it out, and comment out anything that echoes prior. As Ch0cu3r mentioned do not add html, sending json is just for data and not style. Do that if need to optionally when getting the request for display. header('Content-Type: application/json; charset=utf-8'); echo json_encode(array('data' => $output),true); I tried the changes your provided: var_dump($output); prints: array (size=1) 0 => array (size=4) 0 => object(SimpleXMLElement)[9] 1 => object(SimpleXMLElement)[8] 2 => object(SimpleXMLElement)[7] 3 => object(SimpleXMLElement)[10] where $output is $output[] = array($time[0], $temperature[0], $current[0],$wind[0]); while print_r output of the same $output is: Array ( [0] => Array ( [0] => SimpleXMLElement Object ( ) [1] => SimpleXMLElement Object ( ) [2] => SimpleXMLElement Object ( ) [3] => SimpleXMLElement Object ( ) ) ) tried to json econde stil not working.. it only prints when i click on a city that does not exist. is it posible that my array can not be converted to json format? can`t seem to find anything on google about that. Quote Link to comment https://forums.phpfreaks.com/topic/298274-php-array-to-json_encode-not-working/#findComment-1521424 Share on other sites More sharing options...
QuickOldCar Posted September 23, 2015 Share Posted September 23, 2015 Why use the xml version and convert to json when you can use the json one and use that? http://api.wunderground.com/api/KEY/geolookup/conditions/q/us/$city.json json_decode() object $results = json_decode($data); array $results = json_decode($data,true); <?php $key = "your key"; if (isset($_POST['city'])) { $city = $_POST['city']; } else { $city = 'New York'; } $results = file_get_contents("http://api.wunderground.com/api/$key/geolookup/conditions/q/us/$city.json"); header('Content-Type: application/json'); echo $results; ?> Quote Link to comment https://forums.phpfreaks.com/topic/298274-php-array-to-json_encode-not-working/#findComment-1521429 Share on other sites More sharing options...
hansford Posted September 23, 2015 Share Posted September 23, 2015 Can you post what the city.xml file looks like to see if there are any traversing issues. Quote Link to comment https://forums.phpfreaks.com/topic/298274-php-array-to-json_encode-not-working/#findComment-1521432 Share on other sites More sharing options...
Stargate22 Posted September 23, 2015 Author Share Posted September 23, 2015 Can you post what the city.xml file looks like to see if there are any traversing issues. //could not find an attachment option... sorry for spam. o.O <response> <version>0.1</version> <termsofService>http://www.wunderground.com/weather/api/d/terms.html</termsofService> <features> <feature>geolookup</feature> <feature>conditions</feature> </features> <location> <type>CITY</type> <country>US</country> <country_iso3166>US</country_iso3166> <country_name>USA</country_name> <state>NY</state> <city>New York</city> <tz_short>EDT</tz_short> <tz_long>America/New_York</tz_long> <lat>40.75013351</lat> <lon>-73.99700928</lon> <zip>10001</zip> <magic>3</magic> <wmo>99999</wmo> <l>/q/zmw:10001.3.99999</l> <requesturl>US/NY/New_York.html</requesturl> <wuiurl>http://www.wunderground.com/US/NY/New_York.html</wuiurl> <nearby_weather_stations> <airport> <station> <city>Central Park</city> <state>NY</state> <country>US</country> <icao>KNYC</icao> <lat>40.77899933</lat> <lon>-73.96924591</lon> </station> <station> <city>New York Downtown Manhattan/w</city> <state>NY</state> <country>US</country> <icao>KJRB</icao> <lat>40.70121384</lat> <lon>-74.00902557</lon> </station> <station> <city>New York</city> <state>NY</state> <country>US</country> <icao>KLGA</icao> <lat>40.77944565</lat> <lon>-73.88027191</lon> </station> <station> <city>Teterboro</city> <state>NJ</state> <country>US</country> <icao>KTEB</icao> <lat>40.85899353</lat> <lon>-74.05616760</lon> </station> </airport> <pws> <station> <neighborhood>Midtown</neighborhood> <city>New York</city> <state>NY</state> <country>US</country> <id>KNYNEWYO206</id> <lat>40.748192</lat> <lon>-74.001923</lon> <distance_km>0</distance_km> <distance_mi>0</distance_mi> </station> <station> <neighborhood>Midtown</neighborhood> <city>New York</city> <state>NY</state> <country>US</country> <id>KNYNEWYO307</id> <lat>40.745659</lat> <lon>-73.999336</lon> <distance_km>0</distance_km> <distance_mi>0</distance_mi> </station> <station> <neighborhood>Midtown</neighborhood> <city>New York</city> <state>NY</state> <country>US</country> <id>KNYNEWYO324</id> <lat>40.744850</lat> <lon>-73.999626</lon> <distance_km>0</distance_km> <distance_mi>0</distance_mi> </station> <station> <neighborhood>Midtown</neighborhood> <city>New York</city> <state>NY</state> <country>US</country> <id>KNYNEWYO354</id> <lat>40.752243</lat> <lon>-74.004166</lon> <distance_km>0</distance_km> <distance_mi>0</distance_mi> </station> <station> <neighborhood>Midtown</neighborhood> <city>Hoboken</city> <state>NJ</state> <country>US</country> <id>KNJHOBOK4</id> <lat>40.746616</lat> <lon>-74.004456</lon> <distance_km>0</distance_km> <distance_mi>0</distance_mi> </station> <station> <neighborhood>Midtown</neighborhood> <city>New York</city> <state>NY</state> <country>US</country> <id>KNYNEWYO230</id> <lat>40.744087</lat> <lon>-73.990326</lon> <distance_km>0</distance_km> <distance_mi>0</distance_mi> </station> <station> <neighborhood>Midtown</neighborhood> <city>New York</city> <state>NY</state> <country>US</country> <id>KNYNEWYO218</id> <lat>40.743759</lat> <lon>-73.986359</lon> <distance_km>1</distance_km> <distance_mi>0</distance_mi> </station> <station> <neighborhood>Hell's Kitchen</neighborhood> <city>New York</city> <state>NY</state> <country>US</country> <id>KNYNEWYO285</id> <lat>40.760880</lat> <lon>-73.999069</lon> <distance_km>1</distance_km> <distance_mi>0</distance_mi> </station> <station> <neighborhood>Flatiron</neighborhood> <city>New York</city> <state>NY</state> <country>US</country> <id>KNYNEWYO118</id> <lat>40.743301</lat> <lon>-73.985466</lon> <distance_km>1</distance_km> <distance_mi>0</distance_mi> </station> <station> <neighborhood>Murray Hill</neighborhood> <city>New York</city> <state>NY</state> <country>US</country> <id>KNYNEWYO71</id> <lat>40.746399</lat> <lon>-73.981598</lon> <distance_km>1</distance_km> <distance_mi>0</distance_mi> </station> <station> <neighborhood>Hell's Kitchen</neighborhood> <city>New York</city> <state>NY</state> <country>US</country> <id>KNYNEWYO200</id> <lat>40.761570</lat> <lon>-73.989952</lon> <distance_km>1</distance_km> <distance_mi>0</distance_mi> </station> <station> <neighborhood>Midtown West</neighborhood> <city>New York</city> <state>NY</state> <country>US</country> <id>KNYNEWYO343</id> <lat>40.762779</lat> <lon>-73.991776</lon> <distance_km>1</distance_km> <distance_mi>0</distance_mi> </station> <station> <neighborhood>Lower Manhattan</neighborhood> <city>Hoboken</city> <state>NJ</state> <country>US</country> <id>KNJHOBOK12</id> <lat>40.738083</lat> <lon>-74.004951</lon> <distance_km>1</distance_km> <distance_mi>0</distance_mi> </station> <station> <neighborhood>Midtown East</neighborhood> <city>New York</city> <state>NY</state> <country>US</country> <id>KNYNEWYO91</id> <lat>40.752632</lat> <lon>-73.979225</lon> <distance_km>1</distance_km> <distance_mi>0</distance_mi> </station> <station> <neighborhood>Midtown</neighborhood> <city>New York</city> <state>NY</state> <country>US</country> <id>KNYNEWYO165</id> <lat>40.749748</lat> <lon>-73.978706</lon> <distance_km>1</distance_km> <distance_mi>0</distance_mi> </station> <station> <neighborhood>Lower Manhattan</neighborhood> <city>New York</city> <state>NY</state> <country>US</country> <id>KNYNEWYO275</id> <lat>40.735519</lat> <lon>-73.996330</lon> <distance_km>1</distance_km> <distance_mi>0</distance_mi> </station> <station> <neighborhood>Lower Manhattan</neighborhood> <city>Hoboken</city> <state>NJ</state> <country>US</country> <id>KNJHOBOK22</id> <lat>40.734905</lat> <lon>-74.008102</lon> <distance_km>1</distance_km> <distance_mi>1</distance_mi> </station> <station> <neighborhood>Midtown</neighborhood> <city>New York</city> <state>NY</state> <country>US</country> <id>KNYNEWYO359</id> <lat>40.736454</lat> <lon>-73.982727</lon> <distance_km>1</distance_km> <distance_mi>1</distance_mi> </station> <station> <neighborhood>Midtown</neighborhood> <city>New York</city> <state>NY</state> <country>US</country> <id>KNYNEWYO193</id> <lat>40.751450</lat> <lon>-73.978241</lon> <distance_km>1</distance_km> <distance_mi>0</distance_mi> </station> <station> <neighborhood>Theater District</neighborhood> <city>New York</city> <state>NY</state> <country>US</country> <id>KNYNEWYO168</id> <lat>40.761948</lat> <lon>-73.986061</lon> <distance_km>1</distance_km> <distance_mi>0</distance_mi> </station> <station> <neighborhood>Midtown</neighborhood> <city>Long Island City</city> <state>NY</state> <country>US</country> <id>KNYLONGI7</id> <lat>40.746727</lat> <lon>-73.974274</lon> <distance_km>1</distance_km> <distance_mi>1</distance_mi> </station> </pws> </nearby_weather_stations> </location> <current_observation> <image> <url>http://icons.wxug.com/graphics/wu2/logo_130x80.png</url> <title>Weather Underground</title> <link>http://www.wunderground.com</link> </image> <display_location> <full>New York, NY</full> <city>New York</city> <state>NY</state> <state_name>New York</state_name> <country>US</country> <country_iso3166>US</country_iso3166> <zip>10001</zip> <magic>3</magic> <wmo>99999</wmo> <latitude>40.75013351</latitude> <longitude>-73.99700928</longitude> <elevation>17.00000000</elevation> </display_location> <observation_location> <full>Flatiron, New York, New York</full> <city>Flatiron, New York</city> <state>New York</state> <country>US</country> <country_iso3166>US</country_iso3166> <latitude>40.743301</latitude> <longitude>-73.985466</longitude> <elevation>207 ft</elevation> </observation_location> <estimated> </estimated> <station_id>KNYNEWYO118</station_id> <observation_time>Last Updated on September 22, 5:43 PM EDT</observation_time> <observation_time_rfc822>Tue, 22 Sep 2015 17:43:01 -0400</observation_time_rfc822> <observation_epoch>1442958181</observation_epoch> <local_time_rfc822>Tue, 22 Sep 2015 17:43:02 -0400</local_time_rfc822> <local_epoch>1442958182</local_epoch> <local_tz_short>EDT</local_tz_short> <local_tz_long>America/New_York</local_tz_long> <local_tz_offset>-0400</local_tz_offset> <weather>Overcast</weather> <temperature_string>69.6 F (20.9 C)</temperature_string> <temp_f>69.6</temp_f> <temp_c>20.9</temp_c> <relative_humidity>52%</relative_humidity> <wind_string>Calm</wind_string> <wind_dir>NNE</wind_dir> <wind_degrees>22</wind_degrees> <wind_mph>0.0</wind_mph> <wind_gust_mph>0</wind_gust_mph> <wind_kph>0.0</wind_kph> <wind_gust_kph>0</wind_gust_kph> <pressure_mb>1024</pressure_mb> <pressure_in>30.24</pressure_in> <pressure_trend>-</pressure_trend> <dewpoint_string>51 F (11 C)</dewpoint_string> <dewpoint_f>51</dewpoint_f> <dewpoint_c>11</dewpoint_c> <heat_index_string>NA</heat_index_string> <heat_index_f>NA</heat_index_f> <heat_index_c>NA</heat_index_c> <windchill_string>NA</windchill_string> <windchill_f>NA</windchill_f> <windchill_c>NA</windchill_c> <feelslike_string>69.6 F (20.9 C)</feelslike_string> <feelslike_f>69.6</feelslike_f> <feelslike_c>20.9</feelslike_c> <visibility_mi>10.0</visibility_mi> <visibility_km>16.1</visibility_km> <solarradiation>65</solarradiation> <UV>1.0</UV> <precip_1hr_string>0.00 in ( 0 mm)</precip_1hr_string> <precip_1hr_in>0.00</precip_1hr_in> <precip_1hr_metric> 0</precip_1hr_metric> <precip_today_string> in ( mm)</precip_today_string> <precip_today_in></precip_today_in> <precip_today_metric></precip_today_metric> <icon>cloudy</icon> <icon_url>http://icons.wxug.com/i/c/k/cloudy.gif</icon_url> <forecast_url>http://www.wunderground.com/US/NY/New_York.html</forecast_url> <history_url>http://www.wunderground.com/weatherstation/WXDailyHistory.asp?ID=KNYNEWYO118</history_url> <ob_url>http://www.wunderground.com/cgi-bin/findweather/getForecast?query=40.743301,-73.985466</ob_url> </current_observation> </response> Quote Link to comment https://forums.phpfreaks.com/topic/298274-php-array-to-json_encode-not-working/#findComment-1521435 Share on other sites More sharing options...
Barand Posted September 23, 2015 Share Posted September 23, 2015 try foreach($xml->current_observation as $item){ $current = (string)$item->weather; $temperature = (string)$item->temp_c; $time = (string)$item->local_time_rfc822; $wind = (string)$item->wind_string; $humidity = (string)$item->relative_humidity; $output[] = array($time, $temperature, $current, $wind); } 1 Quote Link to comment https://forums.phpfreaks.com/topic/298274-php-array-to-json_encode-not-working/#findComment-1521446 Share on other sites More sharing options...
Stargate22 Posted September 23, 2015 Author Share Posted September 23, 2015 try foreach($xml->current_observation as $item){ $current = (string)$item->weather; $temperature = (string)$item->temp_c; $time = (string)$item->local_time_rfc822; $wind = (string)$item->wind_string; $humidity = (string)$item->relative_humidity; $output[] = array($time, $temperature, $current, $wind); } WOW thank you so much. Now my php output looks readable PHP json_ecoded output is : {"data":[["Thu, 24 Sep 2015 02:00:58 +0300","19.3","Clear","From the West at 1.6 MPH Gusting to 2.5 MPH"]]} My index still does not show any output or error or any kind.. the problem could be in my ajax now.. I will try to find a solution and post it here to. Quote Link to comment https://forums.phpfreaks.com/topic/298274-php-array-to-json_encode-not-working/#findComment-1521448 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.