【发布时间】:2013-05-04 16:57:30
【问题描述】:
我目前正在构建一个 HTML5 应用程序,该应用程序从 php 网络服务获取其数据 json 编码。 我也有存储在数据库中的小图像,并希望将它们返回为使用 json 结果编码的 base64。
目前我得到了所有 mysql 字段,然后像这样以 json 格式返回:
$query = "SELECT * FROM `news` ";
$posts = array();
if(mysql_num_rows($result)) {
while($post = mysql_fetch_assoc($result)) {
$posts[] = array('post'=>$post);
}
}
header('Content-Type: text/javascript');
echo json_encode(array('posts'=>$posts));
我有一个名为图片的字段。 现在我想用base64转换数组posts[]中的图片数据,我可以简单地用json返回所有数据,而不需要只为图片发送另一个http请求。
我的 php 技能不是很好,但我想到了类似的东西:
$posts['picture'] = base64_encode($posts['picture']);
但我需要将每张图片都转换为base64,所以最好把它放在while循环中:
while($post = mysql_fetch_assoc($result)) {
if($post == 'picture'){
$post = base64_encode($post);
}
$posts[] = array('post'=>$post);
}
这行得通吗?还是有其他/更好的方法? 谢谢!
【问题讨论】:
标签: php json html web-services blob