繁体   English   中英

PHP数组到JSON编码不起作用

[英]Php array to json encode not working

我有一个与我的json.php文件的ajax连接,它无法正常工作...您知道发生了什么吗? 是我的$ output变量,它不能转换成json吗,可以是我的Ajax吗? 任何帮助将不胜感激。 PS:当我单击一个不存在的城市时,它会输出$ output变量。当我单击一个不存在的城市时,我什么也没有。 它杀了我。 var_dump($ output){如果未编码}是:

    array (size=1)
  0 => 
    array (size=4)
      0 => 
        object(SimpleXMLElement)[9]
      1 => 
        object(SimpleXMLElement)[8]
      2 => 
        object(SimpleXMLElement)[7]
      3 => 
        object(SimpleXMLElement)[10]

json.php文件:

<?php

if(isset($_POST['city'])){
    $city = $_POST['city']; //checks if variable city is set if not it will be set as default 
    var_dump($city); 
}else{
    $city = 'New York';


}
//loads data as simple xml
$result = "http://api.wunderground.com/api/KEY/geolookup/conditions/q/ro/$city.xml";
$xml = simplexml_load_file($result);
#echo htmlspecialchars($result, ENT_QUOTES, 'UTF-8');
$place = $xml->location->city; //gets the city name
#var_dump($place);
if(!empty($place)){ //checks if city exits
  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); 

}

    }
}else{
    $output = 'No results found, please try a different city.';  //if variable $place is empty it will print this
}

header('Content-Type: application/json; charset=utf-8');
echo json_encode(array('data' => $output),true);
?>

和jQuery文件:

 $(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);
            }
            });

    });
});

编辑1:我已经更新了我的代码,使我的输出经过json编码并等于

{"data":[["Thu, 24 Sep 2015 02:00:58 +0300","19.3","Clear","From the West at 1.6 MPH Gusting to 2.5 MPH"]]}

我认为现在的问题出在我的AJAX中(我是jQuery的新用户),当我单击某个城市时,没有得到任何打印的信息。

很多时候,当我们的数组内容未编码时,就会发生这种情况。 通常,我们使用UTF-8编码。

因此,要解决此问题,您需要添加此内容,

mysqli_set_charset($con, 'utf8');

连接之后。

看看以下教程: https : //lostechies.com/seanbiefeld/2011/10/21/simple-xml-to-json-with-php/

您将进行str_replacetrim然后对网络数据进行编码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM