PHP中生成json信息的方法
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PHP中生成json信息的方法相关的知识,希望对你有一定的参考价值。
1 <?php 2 3 //php中生成json信息 4 //json_encode(数组/对象) 5 6 $color = array(‘red‘,‘blue‘,‘green‘); //【索引数组】 7 echo json_encode($color),"<br />"; //["red","blue","green"] 8 9 $animal = array(‘east‘=>‘tiger‘,‘north‘=>‘wolf‘,‘south‘=>‘monkey‘); //【关联数组】 10 echo json_encode($animal),"<br />";//{"east":"tiger","north":"wolf","south":"monkey"} 11 12 //【索引关联数组】 13 $animal2 = array(‘east‘=>‘tiger‘,‘north‘=>‘wolf‘,‘duck‘,‘south‘=>‘monkey‘); 14 echo json_encode($animal2),"<br />";//{"east":"tiger","north":"wolf","0":"duck","south":"monkey"} 15 16 //[{},{},{}] 17 //{"weatherinfo":{"city":"北京","cityid":"101010100","temp":"9","WD":"南风","WS":"2级","SD":"26%","WSE":"2","time":"10:20","isRadar":"1","Radar":"JC_RADAR_AZ9010_JB","njd":"暂无实况","qy":"1014"}} 18 //{名称:[],名称:[],名称:[]} 19 20 21 //【对象生成json信息】 22 class Person{ 23 public $addr = "beijing"; 24 public $height = 170; 25 public function study(){ 26 echo "study php"; 27 } 28 } 29 $tom = new Person(); 30 //只是对象的属性给生成json信息 31 echo json_encode($tom);//{"addr":"beijing","height":170}
1.json
json_encode(数组/对象)------------>生成json信息,
json_decode(json信息); 反编码json信息
对json字符串信息进行反编码,变为当前语言可以识别的信息。
2. javascript接收处理json信息
通过eval()把接收的json字符串变成真实的对象信息
代码如下:
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 2 <html> 3 <head> 4 <title>新建网页</title> 5 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 6 <meta name="description" content="" /> 7 <meta name="keywords" content="" /> 8 9 <script type="text/javascript"> 10 function showweather(){ 11 //利用ajax获得天气预报信息 12 //利用javascript+dom处理并显示天气信息 13 var xhr = new XMLHttpRequest(); 14 xhr.onreadystatechange = function(){ 15 if(xhr.readyState==4){ 16 //alert(xhr.responseText); 17 console.log(typeof xhr.responseText);//string 18 //要把接收的“字符串”变为“对象” 19 //‘{"addr":"\u5317\u4eac","temp":"9-22","wind":"north4-5"}‘ 20 eval("var info="+xhr.responseText); 21 22 var str = "地址:"+info.addr+";温度:"+info.temp+";风向:"+info.wind; 23 document.getElementById(‘result‘).innerHTML = str; 24 } 25 } 26 xhr.open(‘get‘,‘./03.php‘); 27 xhr.send(null); 28 } 29 window.onload = function(){ 30 showweather(); 31 } 32 33 // //s字符串变为对象obj 34 // var s = "{name:‘tom‘,height:170}"; 35 // //"var obj="+"{name:‘tom‘,height:170}"====>"var obj={name:‘tom‘,height:170}" 36 // //console.log("var obj="+s); 37 // eval("var obj="+s); 38 // console.log(obj);//Object { name="tom", height=170} 39 40 </script> 41 42 <style type="text/css"> 43 </style> 44 </head> 45 <body> 46 <h2>获得天气预报接口信息</h2> 47 <div id="result"></div> 48 </body> 49 </html>
以上是关于PHP中生成json信息的方法的主要内容,如果未能解决你的问题,请参考以下文章
使用在另一个片段(NPE)中生成的值设置片段的 TextView [重复]