使用cURL从REST api获取图像

时间:2014-06-23 17:47:18

标签: php api rest curl

这是     $ picture = curl_exec($ ch);     curl_close($ CH);

1 个答案:

答案 0 :(得分:0)

你不能直接将它注入html,就像你需要两个文件一个用html和一个用图像像这样:

<html>
<head>
    <title>Test</title>
</head>
<body>
    <img src='getimage.php' />
</body>
</html>

然后在您的getimage.php文件中:

<?php 
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'url');

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer xxx'));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$picture = curl_exec($ch);
curl_close($ch);
//Display the image in the browser
header('Content-type: image/jpeg');
echo $picture;
?>

在同一个文件中执行此操作的唯一方法是获取图像,而不是更改文档的标题,并对图像执行base64编码并将其用作src。我相信它会是这样的:

<html>
<head>
<title>Test</title>
</head>
<body>
<?php 
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, 'url');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer xxx'));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$picture = curl_exec($ch);
curl_close($ch);
?>
<img src="data:image/jpg;base64,<?php echo base64_encode($picture); ?>" >
</body></html>