標籤:
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);//string18 //要把接收的“字串”變為“對象”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字串變為對象obj34 // 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資訊的方法