php抓取网页json数据(如下PHP返回简单的json数据的代码实例:把要传递的数据放在一个关联数组中)
优采云 发布时间: 2022-04-14 05:04php抓取网页json数据(如下PHP返回简单的json数据的代码实例:把要传递的数据放在一个关联数组中)
PHP返回的JSON数据既可以与网页交互,也可以与Android端交互。因此,对于 PHP 来说,返回 JSON 数据是比较重要的。最近在做项目的时候,曾经返回JSON数据与Android端进行交互。总结如下:
1.PHP返回简单json数据代码示例:
$array = array('username'=>'博客', 'password'=>'123456',);
echo json_encode($array);
将要传递的数据放在一个关联数组中,然后通过json_encode()函数传递给Android或者网页。
Android端接收json数据的核心代码:
StringBuilder builder = new StringBuilder();
HttpGet myget = new HttpGet("http://127.0.0.1/Android/index.php");
JSONObject jsonObject = new JSONObject(builder.toString());
String re_username = jsonObject.getString("username");
String re_password = jsonObject.getString("password");
2.从数据库中获取多组数据并返回json数据示例:
$getmsg = mysql_query("SELECT username,content FROM message ORDER BY id desc",$con);
$msg = array();
$i = 0;
while ($row = mysql_fetch_assoc($getmsg))
{
$msg[$i] = $row;
$i++;
}
print json_encode($msg);
但是如果数据库中的结果收录中文,那么json_encode()函数会对这些中文进行编码并返回,那么接收到的中文就是编码后的中文,会变成像\5HF这样的Unicode码,那我们怎么做正确显示中文?这个需要先对中文进行urlencode编码,再json_encode编码,接收后再进行urlencode编码,保证中文不显示的问题,可以封装成一个函数:
function arrayRecursive(&$array, $function, $apply_to_keys_also = false)
{
static $recursive_counter = 0;
if (++$recursive_counter > 1000)
{
die('possible deep recursion attack');
}
foreach ($array as $key => $value)
{
if (is_array($value))
{
arrayRecursive($array[$key], $function, $apply_to_keys_also);
}
else
{
$array[$key] = $function($value);
}
if ($apply_to_keys_also && is_string($key))
{
$new_key = $function($key);
if ($new_key != $key)
{
$array[$new_key] = $array[$key];
unset($array[$key]);
}
}
}
$recursive_counter--;
}
然后使用这个函数对数组进行操作:
function json1($array)
{
arrayRecursive($array, 'urlencode', true);
$json = json_encode($array);
return urldecode($json);
}
那么从上面的数据库中取出的$msg就可以放在这个函数中,传递给Android端了:
print json1($msg);
这样就解决了中文编码的问题。 (注意页面和数据库端中文的编码应该是utf-8)
我的经验仅供参考!