我的PHP类返回一个小的base64编码图像,链接:
class Service
{
function getLogo()
{
$image = "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c
QAAAARnQU1BAACxjwv8YQUAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwA";
return 'data:image/png;base64,' . $image;
}
}
使用json_encode
返回图片会在\n
的每一行后添加$image
:
$service = new Service();
$response = array('name' => $service->getName(), 'logo' => $service->getLogo());
header('Content-type: application/json');
echo json_encode($response);
如何正确处理?
答案 0 :(得分:5)
你通过将它分成两行来破坏你的base64数据。它应该是
function getLogo() {
$image = "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4cQAAAARnQU1BAACxjwv8YQUAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwA";
return 'data:image/png;base64,' . $image;
}
没有换行符。
答案 1 :(得分:2)
答案由Marc B.给出。这只是一个评论。如果代码格式确实 对你很重要,你不能容忍长行(为什么?),那么你总是可以格式化PHP:
class Service
{
function getLogo()
{
$image = 'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c';
$image .= 'QAAAARnQU1BAACxjwv8YQUAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwA';
return 'data:image/png;base64,' . $image;
}
}