我试图这样做: 加载http://example.com/nickname/picture(昵称作为你访问的网址中的var加载,这是有效的) 解码到json 这个网站是
{
"picture": "https://example.com/hf8329yrh8oq.jpg"
}
加载图片 我尝试了什么:
function curlGet($url)
{
$crl = curl_init();
$timeout = 5;
curl_setopt ($crl, CURLOPT_URL,$url);
curl_setopt ($crl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($crl, CURLOPT_CONNECTTIMEOUT, $timeout);
$status = curl_exec($crl);
curl_close($crl);
return $status;
}
$profPicCurl = curlGet('https://example.com/'.urlencode($_GET['nickname']).'/picture')
$profPic = json_decode($profPicCurl,true);
echo file_get_contents($profPic.["picture"]);
我知道我没有在这个脚本中处理错误和内容,但我希望它能够先用真实图像处理。
所以平均问题:如何从解码的json网站显示和成像?
答案 0 :(得分:0)
你真的需要curl
吗?
您也可以在我的代码中将file_get_contents
替换为curlGet
<?php
$profPic = json_decode( file_get_contents( 'https://example.com/'.urlencode( $_GET['nickname'] ).'/picture' ) );
if ( $profPic ) { // is a valid json object
if ( isset( $profPic->picture ) ) { // profile picture exists
$profPic = $profPic->picture;
$extension = strtolower( pathinfo( $profPic, PATHINFO_EXTENSION ) ); // get the image extension
$content = file_get_contents( $profPic ); // get content of image
if ( $content ) {
header( "Content-type: image/".$extension ); // set mime type
echo $content; // output the content
exit();
}
}
}
echo "File not found"; // there is some errors :\
?>
答案 1 :(得分:0)
function getUserImage($nick, $imgUrl = false) {
$jsonString = file_get_contents("http://example.com/".$nickname."/picture");
$json = json_decode($jsonString);
if ($imgUrl){
return $json->picture;
} else {
return file_get_contents($json->picture);
}
};
然后使用
<?php
header("Content_Type: image/jpeg");
echo getUserImage("quagmire");
或
<img src="<?= getUrlImage("quagmire", true) ?>"/>