如何从API获取数据 - php - curl

时间:2017-02-24 05:17:07

标签: php api curl

如何从api url获取数据(图像)?

Api结果:

info = { "title" : "aaaaa", "image" : "bbbbb" };

Api网址:

http://www.example.com/api

代码:

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/api');
$result = curl_exec($ch);
curl_close($ch);
$obj = json_decode($result);
echo $result->image;
?>
Array
(
    [curlResult] => info = { "title" : "aaaaa", "image" : "bbbbb" };
    [info] => Array
        (
            [url] => http://127.0.0.1/api.txt
            [content_type] => text/plain
            [http_code] => 200
            [header_size] => 237
            [request_size] => 55
            [filetime] => -1
            [ssl_verify_result] => 0
            [redirect_count] => 0
            [total_time] => 0
            [namelookup_time] => 0
            [connect_time] => 0
            [pretransfer_time] => 0
            [size_upload] => 0
            [size_download] => 48
            [speed_download] => 48
            [speed_upload] => 0
            [download_content_length] => 48
            [upload_content_length] => 0
            [starttransfer_time] => 0
            [redirect_time] => 0
            [certinfo] => Array
                (
                )

            [primary_ip] => 127.0.0.1
            [primary_port] => 80
            [local_ip] => 127.0.0.1
            [local_port] => 61662
            [redirect_url] => 
        )

    [errno] => 0
    [error] => 
)

2 个答案:

答案 0 :(得分:0)

视图像是否为实际blob内容或url链接可能会改变显示图像的方式。

如果是内容,则需要获取MIME类型才能正确显示,以便设置正确的页眉。

如果是链接,请访问该网页。

答案 1 :(得分:0)

在你的api中:

  1. 将整个图片内容读取为字符串。 (的file_get_contents)
  2. 将其编码为base64字符串。 (BASE64_ENCODE)
  3. 将其添加到返回结果中。 (替换“image”=“bbbbb”)
  4. 这看起来:

    $result = array(
        "title" => "aaaaa",
        "image" => "bbbbb"
    );
    $result["image"] = file_get_contents("path/to/your/image/file");
    $result["image"] = base64_encode($result["image"]);
    $result = json_encode($result);
    header("Content-Type: application/json");
    echo $result;
    

    在您的代码中:

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/api');
    $result = curl_exec($ch);
    curl_close($ch);
    $obj = json_decode($result);
    // Do it if you encoded image string
    $image_string = base64_decode($obj->image);
    // Create image from base 64 decoded string
    $image = imagecreatefromstring($image_string);
    // And save your image as desired type (png or jpeg)
    imagepng($image, "path/to/save/your/image/as/png");
    

    编辑:你能提供服务器端代码吗?您所使用的代码按预期工作在哪里?