Cách nhận phản hồi từ api trong php

Các yêu cầu HTTP là một đặc điểm nổi bật của các ứng dụng dựa trên web, hiện đại—đặc biệt là trong PHP. Chúng tôi phải tương tác với tất cả các loại API và dịch vụ bên ngoài, chẳng hạn như Google Cloud, Facebook và AWS, gần như hàng ngày. Tôi muốn nói rằng nó có thể là một trong những điều đầu tiên bạn học được sau khi bạn đã thành thạo nền tảng của PHP. nó dành cho tôi

Điều đó nói rằng, giống như nhiều ngôn ngữ phát triển phần mềm hiện đại, có nhiều cách để thực hiện các yêu cầu HTTP. Vì vậy, trong bài đăng này, tôi sẽ giới thiệu cho bạn năm tùy chọn phổ biến nhất để tạo chúng trong PHP. Tôi sẽ chỉ cách sử dụng chúng và đề cập đến một số điểm mạnh và điểm yếu tương ứng của chúng. Tôi sẽ không khám phá chúng một cách chi tiết, thay vào đó sẽ giới thiệu rộng rãi về từng thứ

Các cách tiếp cận mà tôi sẽ đề cập là

  • Trình bao bọc luồng HTTP/s của PHP
  • Phần mở rộng cURL của PHP
  • GuzzleHttp
  • Httpful
  • Máy khách HTTP của Symfony

Với mỗi cái, chúng ta sẽ xem qua một ví dụ mã sẽ tải xuống tuyển chọn 10 hình ảnh của Vườn quốc gia Kakadu (ở Úc) bằng cách sử dụng API của Flickr, chẳng hạn như hình bên dưới

Cách nhận phản hồi từ api trong php

“Hoàng hôn trên vùng nước màu vàng Billabong, Công viên quốc gia Kakadu, NT, Úc” của Geoff Whalan, được cấp phép theo CC BY-NC-ND 2. 0

điều kiện tiên quyết

Để hoàn thành hướng dẫn, bạn sẽ cần những thứ sau

  • PHP7. 4 hoặc mới hơn (lý tưởng là phiên bản 8) với các tiện ích mở rộng cURL và OpenSSL được cài đặt và bật, đồng thời bật cài đặt thời gian chạy allow_url_fopen
  • Trình soạn nhạc được cài đặt trên toàn cầu
  • Git (cần thiết để Composer hoạt động đầy đủ)
  • tiếng kêu
  • Tài khoản Flickr và khóa API Flickr

Trước khi chúng tôi bắt đầu

Trong suốt hướng dẫn này, chúng ta sẽ tạo năm tập lệnh PHP, tuy nhiên, trước khi bắt đầu, chúng ta cần thực hiện một số điều

  • Tạo một thư mục dự án
  • Cài đặt PHP dotenv
  • Thêm khóa API Flickr của chúng tôi vào một. env để chúng tôi không vô tình lưu trữ nó trong mã ví dụ

Để hoàn thành hai lệnh đầu tiên, hãy chạy ba lệnh bên dưới

mkdir -p php-http/photos
cd php-http
composer require vlucas/phpdotenv

Tiếp theo, trong thư mục dự án, tạo một tệp mới có tên. env và trong tệp đó, hãy chèn mã bên dưới. Thay thế trình giữ chỗ,

API_KEY=
4, bằng khóa API Flickr của bạn

API_KEY=

Với điều đó, chúng tôi đã sẵn sàng để bắt đầu

Chức năng & tiện ích mở rộng PHP cốt lõi

Hãy bắt đầu với các tùy chọn có sẵn như một phần của chức năng cốt lõi và tiện ích mở rộng của PHP

Trình bao bọc luồng HTTP/S

Trích dẫn hướng dẫn sử dụng PHP

Cho phép truy cập chỉ đọc vào tệp/tài nguyên qua HTTP 1. 0, sử dụng phương thức HTTP GET. Tiêu đề
API_KEY=
5 được gửi cùng với yêu cầu xử lý máy chủ ảo dựa trên tên. Nếu bạn đã định cấu hình chuỗi user_agent bằng php của mình. ini hoặc bối cảnh luồng, nó cũng sẽ được đưa vào yêu cầu

Vì các luồng là một phần cốt lõi của PHP, bạn không cần phải làm gì nhiều để tận dụng chức năng của chúng. Hơn nữa, chúng tích hợp với nhiều chức năng cốt lõi của PHP, chẳng hạn như fopen và file_get_contents. Do đó, bạn không cần cài đặt thư viện của bên thứ ba hoặc tiện ích mở rộng tùy chỉnh để bắt đầu sử dụng nó

Mặt khác, chúng không có giao diện trực quan cũng như các phương thức tiện ích của trình trợ giúp mà các thư viện bên thứ ba như GuzzleHttp và ứng dụng khách HTTP của Symfony có. Ngoài ra, nó

  • Chỉ hỗ trợ đọc (NHẬN) không ghi (POST, PUT và DELETE), các yêu cầu
  • Chỉ hỗ trợ một số tùy chọn ngữ cảnh hạn chế, chẳng hạn như tác nhân người dùng, chuyển hướng, tiêu đề, thời gian chờ và proxy. Điều đó nói rằng, bạn có thể làm khá nhiều với những

Ghi chú. Tùy thuộc vào trường hợp sử dụng của bạn, bị giới hạn ở HTTP/1. 0 có thể là một vấn đề. Tuy nhiên, trong năm ví dụ trong hướng dẫn này, nó không phải là. Nếu bạn muốn tìm hiểu thêm về sự khác biệt giữa HTTP 1. 0, 1. 1. và 2, hãy xem bài đăng xuất sắc này từ Digital Ocean

Điều đó nói rằng, bạn có thể bắt đầu và chạy nó khá nhanh. Hãy xem qua một ví dụ về cách thực hiện. Trong thư mục php-http, tạo một tệp PHP trống có tên http-stream. php và trong đó, dán mã bên dưới

load();

const BASE_URL = 'https://api.flickr.com/services';
const PHOTO_URL = 'https://live.staticflickr.com/%s/%s_%s_b.jpg';
const PHOTOS_DIR = 'photos';

$apiKey=$_ENV['API_KEY'];

$opts = [
    'https' => [
        'max_redirects' => 3,
    ],
];
$queryString = http_build_query([
    'api_key' => $apiKey,
    'content_type' => 1,
    'format' => 'php_serial',
    'media' => 'photos',
    'method' => 'flickr.photos.search',
    'per_page' => 10,
    'safe_search' => 1,
    'text' => 'Kakadu National Park'
]);
$requestUri = sprintf(
    '%s/rest/?%s',
    BASE_URL,
    $queryString
);
$fp = fopen($requestUri, 'r');

$photoData = unserialize(stream_get_contents($fp));

foreach ($photoData['photos']['photo'] as $photoDatum) {
    printf("Downloading %s.jpg\n", $photoDatum['title']);
    $photoFile = file_get_contents(
        sprintf(
            PHOTO_URL,
            $photoDatum['server'],
            $photoDatum['id'],
            $photoDatum['secret']
        )
    );
    file_put_contents(PHOTOS_DIR . '/' . $photoDatum['title'] . '.jpg', $photoFile);
    printf("  Downloaded %s.jpg\n", $photoDatum['title']);
}

fclose($fp);

Trước tiên, đoạn mã trên xác định một tập hợp các hằng số mà tập lệnh sẽ sử dụng để tương tác với API của Flickr và để lưu các hình ảnh đã tải xuống

Sau đó, vì trình bao bọc luồng không cung cấp cách riêng để tạo chuỗi truy vấn HTTP, nên một chuỗi được tạo bằng cách sử dụng hàm http_build_query của PHP. Ngoài ra, chúng tôi có thể sử dụng nối chuỗi gốc hoặc sprintf, nhưng

API_KEY=
6 sạch hơn và trực quan hơn

Sau đó, fopen được sử dụng để tạo kết nối HTTP chỉ đọc tới API của Flickr. Sau đó, stream_get_contents truy xuất nội dung của yêu cầu, sau đó được hủy xác thực thành một đối tượng PHP cũ đơn giản

Nói tóm lại, hai lời gọi hàm này thực hiện yêu cầu tìm kiếm ảnh minh bạch dựa trên API của Flickr và tải xuống tối đa 10 hình ảnh. Nếu có kết quả cho yêu cầu, thì chúng sẽ được tải xuống bằng cách gọi file_get_contents và được ghi vào hệ thống tệp cục bộ bằng file_put_contents

Bạn có thể nói nhiều điều về PHP, nhưng chắc chắn rằng nó cực kỳ linh hoạt và có sức chứa. Khả năng sử dụng các hàm PHP hiện có là một điều tích cực nhất định, ngay cả khi trong trường hợp này, tên hàm không trực quan nhất cho những gì đang được thực hiện. Tuy nhiên, bằng cách sử dụng trình bao bọc luồng, không yêu cầu phụ thuộc bổ sung, vì vậy bạn có thể thiết lập và chạy khá nhanh

Kiểm tra xem mã có hoạt động không

Bây giờ mã đã được viết, hãy kiểm tra để đảm bảo mã hoạt động. Để làm điều đó, hãy chạy các lệnh bên dưới

php http-stream.php

Bạn sẽ thấy đầu ra tương tự như ví dụ bên dưới

Downloading Happy Snappy.jpg
  Downloaded Happy Snappy.jpg
Downloading Miyumba (Riversleigh World Heritage Area, North West Queensland).jpg
  Downloaded Miyumba (Riversleigh World Heritage Area, North West Queensland).jpg
Downloading Riversleigh Fossil Exploration: Site D (Riversleigh World Heritage Area, North West Queensland).jpg
  Downloaded Riversleigh Fossil Exploration: Site D (Riversleigh World Heritage Area, North West Queensland).jpg
Downloading Miyumba (Riversleigh World Heritage Area, North West Queensland).jpg
  Downloaded Miyumba (Riversleigh World Heritage Area, North West Queensland).jpg
Downloading Black-tailed Treecreeper (Climacteris melanurus melanurus).jpg
  Downloaded Black-tailed Treecreeper (Climacteris melanurus melanurus).jpg
Downloading Wilkins' Rock-Wallaby (Petrogale wilkinsi).jpg
  Downloaded Wilkins' Rock-Wallaby (Petrogale wilkinsi).jpg
Downloading Red-tailed Black Cockatoo.jpg
  Downloaded Red-tailed Black Cockatoo.jpg
Downloading 790515Tu-AyersRock-OU34a-bus-RSmith-ss.jpg
  Downloaded 790515Tu-AyersRock-OU34a-bus-RSmith-ss.jpg
Downloading Spotted Nightjar (Eurostopodus argus).jpg
  Downloaded Spotted Nightjar (Eurostopodus argus).jpg
Downloading Chestnut-quilled Rock Pigeon (Petrophassa rufipennis).jpg
  Downloaded Chestnut-quilled Rock Pigeon (Petrophassa rufipennis).jpg

Sau khi lệnh hoàn thành, nếu bạn tìm trong thư mục ảnh, bạn sẽ thấy mười tệp JPEG

Phần mở rộng cURL của PHP

Tiếp theo, hãy xem cách thực hiện điều tương tự bằng tiện ích mở rộng cURL của PHP. Trước khi chúng tôi có thể bắt đầu, hãy kiểm tra xem tiện ích mở rộng cURL có sẵn trong thời gian chạy PHP của bạn hay không bằng cách chạy lệnh sau

________số 8

Nếu tiện ích mở rộng được cài đặt và bật, bạn sẽ thấy “cURL support => enable” được in trên thiết bị đầu cuối. Tạo một tệp mới trong thư mục dự án có tên là curl. php và sao chép mã dưới đây vào nó

load();

// .. constants, the call to http_build_query, and definition of $requestUri, and $queryString

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $requestUri);
curl_setopt($ch, CURLOPT_SSH_COMPRESSION, true);
curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_URL => $requestUri
]);
$result = curl_exec($ch);
$photoData = unserialize($result);

curl_close($ch);

foreach ($photoData['photos']['photo'] as $photoDatum) {
    printf("Downloading %s.jpg\n", $photoDatum['title']);
    $file_url = sprintf(
        PHOTO_URL,
        $photoDatum['server'],
        $photoDatum['id'],
        $photoDatum['secret']
    );
    $destination_path = PHOTOS_DIR . '/' . $photoDatum['title'] . '.jpg';

    $fp = fopen($destination_path, "w");
    $ch = curl_init($file_url);
    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_exec($ch);
    $st_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    fclose($fp);
    printf("  Downloaded %s.jpg\n", $photoDatum['title']);
}

Ghi chú. Trong mã ví dụ ở trên, tôi đã cố tình không bao gồm các hằng số, lệnh gọi đến

API_KEY=
6 và định nghĩa của
API_KEY=
8, vì chúng giống như trong ví dụ về luồng. Đảm bảo rằng bạn sao chép chúng từ ví dụ về luồng nếu bạn đang theo dõi cục bộ

Để bắt đầu, chúng ta phải gọi curl_init để khởi tạo phiên cURL. Điều này cung cấp một tay cầm mà mã còn lại yêu cầu để thực hiện các yêu cầu HTTP. Sau đó, hai tùy chọn được thiết lập

  • API_KEY=
    
    9. Điều này hướng dẫn cURL trả về kết quả của một yêu cầu thay vì lặp lại nó ngay lập tức
  • load();
    
    const BASE_URL = 'https://api.flickr.com/services';
    const PHOTO_URL = 'https://live.staticflickr.com/%s/%s_%s_b.jpg';
    const PHOTOS_DIR = 'photos';
    
    $apiKey=$_ENV['API_KEY'];
    
    $opts = [
        'https' => [
            'max_redirects' => 3,
        ],
    ];
    $queryString = http_build_query([
        'api_key' => $apiKey,
        'content_type' => 1,
        'format' => 'php_serial',
        'media' => 'photos',
        'method' => 'flickr.photos.search',
        'per_page' => 10,
        'safe_search' => 1,
        'text' => 'Kakadu National Park'
    ]);
    $requestUri = sprintf(
        '%s/rest/?%s',
        BASE_URL,
        $queryString
    );
    $fp = fopen($requestUri, 'r');
    
    $photoData = unserialize(stream_get_contents($fp));
    
    foreach ($photoData['photos']['photo'] as $photoDatum) {
        printf("Downloading %s.jpg\n", $photoDatum['title']);
        $photoFile = file_get_contents(
            sprintf(
                PHOTO_URL,
                $photoDatum['server'],
                $photoDatum['id'],
                $photoDatum['secret']
            )
        );
        file_put_contents(PHOTOS_DIR . '/' . $photoDatum['title'] . '.jpg', $photoFile);
        printf("  Downloaded %s.jpg\n", $photoDatum['title']);
    }
    
    fclose($fp);
    
    0. Điều này đặt URL để yêu cầu

Cả hai tùy chọn này đều được đặt riêng. Tuy nhiên, chúng ta có thể đặt chúng trong một cuộc gọi bằng cách sử dụng curl_setopt_array, như trong ví dụ bên dưới

API_KEY=
4

Với cURL được định cấu hình, curl_exec được gọi để thực hiện yêu cầu tới Flickr API, lưu trữ kết quả trong

load();

const BASE_URL = 'https://api.flickr.com/services';
const PHOTO_URL = 'https://live.staticflickr.com/%s/%s_%s_b.jpg';
const PHOTOS_DIR = 'photos';

$apiKey=$_ENV['API_KEY'];

$opts = [
    'https' => [
        'max_redirects' => 3,
    ],
];
$queryString = http_build_query([
    'api_key' => $apiKey,
    'content_type' => 1,
    'format' => 'php_serial',
    'media' => 'photos',
    'method' => 'flickr.photos.search',
    'per_page' => 10,
    'safe_search' => 1,
    'text' => 'Kakadu National Park'
]);
$requestUri = sprintf(
    '%s/rest/?%s',
    BASE_URL,
    $queryString
);
$fp = fopen($requestUri, 'r');

$photoData = unserialize(stream_get_contents($fp));

foreach ($photoData['photos']['photo'] as $photoDatum) {
    printf("Downloading %s.jpg\n", $photoDatum['title']);
    $photoFile = file_get_contents(
        sprintf(
            PHOTO_URL,
            $photoDatum['server'],
            $photoDatum['id'],
            $photoDatum['secret']
        )
    );
    file_put_contents(PHOTOS_DIR . '/' . $photoDatum['title'] . '.jpg', $photoFile);
    printf("  Downloaded %s.jpg\n", $photoDatum['title']);
}

fclose($fp);
1. Sau đó, phản hồi không được đánh số thứ tự thành một đối tượng PHP cũ đơn giản, như trong ví dụ trước và curl_close được gọi để đóng phiên cURL và giải phóng tất cả các tài nguyên được liên kết

Với phản hồi được trả về, mã sau đó sẽ lặp lại và tải xuống từng hình ảnh trong số 10 hình ảnh. Quá trình này khá giống với ví dụ về luồng và có thể đã sử dụng nguyên văn mã tải xuống. Tuy nhiên, tôi muốn hiển thị một triển khai cụ thể hơn cho cURL

Trong ví dụ này, mã sẽ mở một bộ xử lý tệp để ghi, tải xuống nội dung tệp và ghi nó vào tệp mới, sau đó đóng cả phiên cuộn tròn và bộ xử lý tệp sau khi làm như vậy

Việc ghi dữ liệu hình ảnh vào tệp được đơn giản hóa bằng cách gọi

load();

const BASE_URL = 'https://api.flickr.com/services';
const PHOTO_URL = 'https://live.staticflickr.com/%s/%s_%s_b.jpg';
const PHOTOS_DIR = 'photos';

$apiKey=$_ENV['API_KEY'];

$opts = [
    'https' => [
        'max_redirects' => 3,
    ],
];
$queryString = http_build_query([
    'api_key' => $apiKey,
    'content_type' => 1,
    'format' => 'php_serial',
    'media' => 'photos',
    'method' => 'flickr.photos.search',
    'per_page' => 10,
    'safe_search' => 1,
    'text' => 'Kakadu National Park'
]);
$requestUri = sprintf(
    '%s/rest/?%s',
    BASE_URL,
    $queryString
);
$fp = fopen($requestUri, 'r');

$photoData = unserialize(stream_get_contents($fp));

foreach ($photoData['photos']['photo'] as $photoDatum) {
    printf("Downloading %s.jpg\n", $photoDatum['title']);
    $photoFile = file_get_contents(
        sprintf(
            PHOTO_URL,
            $photoDatum['server'],
            $photoDatum['id'],
            $photoDatum['secret']
        )
    );
    file_put_contents(PHOTOS_DIR . '/' . $photoDatum['title'] . '.jpg', $photoFile);
    printf("  Downloaded %s.jpg\n", $photoDatum['title']);
}

fclose($fp);
2, ghi dữ liệu hình ảnh vào tệp thay vì STDOUT

Ví dụ này nêu bật cách tiện ích mở rộng cURL phù hợp hơn để thực hiện các yêu cầu HTTP so với trình bao bọc luồng. Nó cũng cho thấy cách tiện ích mở rộng cURL có thể định cấu hình và mạnh hơn nhiều, có khả năng. Ngoài ra, các hằng số được xác định trước khá logic và trực quan

Một điều đáng chú ý khác là nhiều gói của bên thứ ba, chẳng hạn như ứng dụng khách HTTP của GuzzleHttp và Symfony sử dụng tiện ích mở rộng cURL trong nội bộ. Do đó, đây là một tiện ích mở rộng đã được thử nghiệm thực tế mà bạn có thể đang sử dụng—ngay cả khi bạn không trực tiếp biết về nó

Ghi chú. Đảm bảo rằng bạn kiểm tra xem mã có hoạt động không

Gói HTTP PHP của bên thứ ba

Bây giờ chúng ta đã xem xét hai cách gốc để thực hiện các yêu cầu HTTPS trong PHP, hãy xem cách thực hiện bằng cách sử dụng ba trong số các gói bên thứ ba nổi tiếng nhất

GuzzleHttp

Được tạo bởi Michael Dowling, GuzzleHttp có lẽ là thư viện bên thứ ba nổi tiếng và được sử dụng nhiều nhất mà tôi sẽ trình bày trong hướng dẫn này

Đây là một chút chuyện nhỏ. Bạn có biết rằng nếu bạn đang sử dụng ứng dụng khách HTTP của Laravel, thì bạn đang sử dụng GuzzleHttp ngầm không?

Để cài đặt thư viện, hãy chạy lệnh bên dưới trong thư mục gốc của dự án

API_KEY=
7

Sau đó, tạo một tệp mới trong thư mục dự án có tên là guzzlehttp. php và sao chép mã dưới đây vào nó

API_KEY=
8

Ghi chú. Tôi đã bỏ qua các hằng số để rút gọn ví dụ

Ví dụ này dài hơn một chút so với hai ví dụ trước, tuy nhiên, đó không hẳn là một điều xấu. Nó bắt đầu bằng cách khởi tạo một mảng chứa một tập hợp các tùy chọn yêu cầu

  • load();
    
    const BASE_URL = 'https://api.flickr.com/services';
    const PHOTO_URL = 'https://live.staticflickr.com/%s/%s_%s_b.jpg';
    const PHOTOS_DIR = 'photos';
    
    $apiKey=$_ENV['API_KEY'];
    
    $opts = [
        'https' => [
            'max_redirects' => 3,
        ],
    ];
    $queryString = http_build_query([
        'api_key' => $apiKey,
        'content_type' => 1,
        'format' => 'php_serial',
        'media' => 'photos',
        'method' => 'flickr.photos.search',
        'per_page' => 10,
        'safe_search' => 1,
        'text' => 'Kakadu National Park'
    ]);
    $requestUri = sprintf(
        '%s/rest/?%s',
        BASE_URL,
        $queryString
    );
    $fp = fopen($requestUri, 'r');
    
    $photoData = unserialize(stream_get_contents($fp));
    
    foreach ($photoData['photos']['photo'] as $photoDatum) {
        printf("Downloading %s.jpg\n", $photoDatum['title']);
        $photoFile = file_get_contents(
            sprintf(
                PHOTO_URL,
                $photoDatum['server'],
                $photoDatum['id'],
                $photoDatum['secret']
            )
        );
        file_put_contents(PHOTOS_DIR . '/' . $photoDatum['title'] . '.jpg', $photoFile);
        printf("  Downloaded %s.jpg\n", $photoDatum['title']);
    }
    
    fclose($fp);
    
    3. Điều này cho phép đầu ra gỡ lỗi;
  • load();
    
    const BASE_URL = 'https://api.flickr.com/services';
    const PHOTO_URL = 'https://live.staticflickr.com/%s/%s_%s_b.jpg';
    const PHOTOS_DIR = 'photos';
    
    $apiKey=$_ENV['API_KEY'];
    
    $opts = [
        'https' => [
            'max_redirects' => 3,
        ],
    ];
    $queryString = http_build_query([
        'api_key' => $apiKey,
        'content_type' => 1,
        'format' => 'php_serial',
        'media' => 'photos',
        'method' => 'flickr.photos.search',
        'per_page' => 10,
        'safe_search' => 1,
        'text' => 'Kakadu National Park'
    ]);
    $requestUri = sprintf(
        '%s/rest/?%s',
        BASE_URL,
        $queryString
    );
    $fp = fopen($requestUri, 'r');
    
    $photoData = unserialize(stream_get_contents($fp));
    
    foreach ($photoData['photos']['photo'] as $photoDatum) {
        printf("Downloading %s.jpg\n", $photoDatum['title']);
        $photoFile = file_get_contents(
            sprintf(
                PHOTO_URL,
                $photoDatum['server'],
                $photoDatum['id'],
                $photoDatum['secret']
            )
        );
        file_put_contents(PHOTOS_DIR . '/' . $photoDatum['title'] . '.jpg', $photoFile);
        printf("  Downloaded %s.jpg\n", $photoDatum['title']);
    }
    
    fclose($fp);
    
    4. Mảng kết hợp này được sử dụng để tạo chuỗi truy vấn cho yêu cầu mà không cần phải gọi http_build_query

Sau đó, một đối tượng

load();

const BASE_URL = 'https://api.flickr.com/services';
const PHOTO_URL = 'https://live.staticflickr.com/%s/%s_%s_b.jpg';
const PHOTOS_DIR = 'photos';

$apiKey=$_ENV['API_KEY'];

$opts = [
    'https' => [
        'max_redirects' => 3,
    ],
];
$queryString = http_build_query([
    'api_key' => $apiKey,
    'content_type' => 1,
    'format' => 'php_serial',
    'media' => 'photos',
    'method' => 'flickr.photos.search',
    'per_page' => 10,
    'safe_search' => 1,
    'text' => 'Kakadu National Park'
]);
$requestUri = sprintf(
    '%s/rest/?%s',
    BASE_URL,
    $queryString
);
$fp = fopen($requestUri, 'r');

$photoData = unserialize(stream_get_contents($fp));

foreach ($photoData['photos']['photo'] as $photoDatum) {
    printf("Downloading %s.jpg\n", $photoDatum['title']);
    $photoFile = file_get_contents(
        sprintf(
            PHOTO_URL,
            $photoDatum['server'],
            $photoDatum['id'],
            $photoDatum['secret']
        )
    );
    file_put_contents(PHOTOS_DIR . '/' . $photoDatum['title'] . '.jpg', $photoFile);
    printf("  Downloaded %s.jpg\n", $photoDatum['title']);
}

fclose($fp);
5 mới được khởi tạo, với một mảng kết hợp được chuyển đến hàm tạo của nó, chứa một cặp khóa/giá trị.
load();

const BASE_URL = 'https://api.flickr.com/services';
const PHOTO_URL = 'https://live.staticflickr.com/%s/%s_%s_b.jpg';
const PHOTOS_DIR = 'photos';

$apiKey=$_ENV['API_KEY'];

$opts = [
    'https' => [
        'max_redirects' => 3,
    ],
];
$queryString = http_build_query([
    'api_key' => $apiKey,
    'content_type' => 1,
    'format' => 'php_serial',
    'media' => 'photos',
    'method' => 'flickr.photos.search',
    'per_page' => 10,
    'safe_search' => 1,
    'text' => 'Kakadu National Park'
]);
$requestUri = sprintf(
    '%s/rest/?%s',
    BASE_URL,
    $queryString
);
$fp = fopen($requestUri, 'r');

$photoData = unserialize(stream_get_contents($fp));

foreach ($photoData['photos']['photo'] as $photoDatum) {
    printf("Downloading %s.jpg\n", $photoDatum['title']);
    $photoFile = file_get_contents(
        sprintf(
            PHOTO_URL,
            $photoDatum['server'],
            $photoDatum['id'],
            $photoDatum['secret']
        )
    );
    file_put_contents(PHOTOS_DIR . '/' . $photoDatum['title'] . '.jpg', $photoFile);
    printf("  Downloaded %s.jpg\n", $photoDatum['title']);
}

fclose($fp);
6. Giá trị của khóa này là một URL cơ sở được thêm vào trước tất cả các yêu cầu sử dụng đối tượng

Với đối tượng

load();

const BASE_URL = 'https://api.flickr.com/services';
const PHOTO_URL = 'https://live.staticflickr.com/%s/%s_%s_b.jpg';
const PHOTOS_DIR = 'photos';

$apiKey=$_ENV['API_KEY'];

$opts = [
    'https' => [
        'max_redirects' => 3,
    ],
];
$queryString = http_build_query([
    'api_key' => $apiKey,
    'content_type' => 1,
    'format' => 'php_serial',
    'media' => 'photos',
    'method' => 'flickr.photos.search',
    'per_page' => 10,
    'safe_search' => 1,
    'text' => 'Kakadu National Park'
]);
$requestUri = sprintf(
    '%s/rest/?%s',
    BASE_URL,
    $queryString
);
$fp = fopen($requestUri, 'r');

$photoData = unserialize(stream_get_contents($fp));

foreach ($photoData['photos']['photo'] as $photoDatum) {
    printf("Downloading %s.jpg\n", $photoDatum['title']);
    $photoFile = file_get_contents(
        sprintf(
            PHOTO_URL,
            $photoDatum['server'],
            $photoDatum['id'],
            $photoDatum['secret']
        )
    );
    file_put_contents(PHOTOS_DIR . '/' . $photoDatum['title'] . '.jpg', $photoFile);
    printf("  Downloaded %s.jpg\n", $photoDatum['title']);
}

fclose($fp);
5 được khởi tạo, một yêu cầu được thực hiện bằng cách gọi phương thức
load();

const BASE_URL = 'https://api.flickr.com/services';
const PHOTO_URL = 'https://live.staticflickr.com/%s/%s_%s_b.jpg';
const PHOTOS_DIR = 'photos';

$apiKey=$_ENV['API_KEY'];

$opts = [
    'https' => [
        'max_redirects' => 3,
    ],
];
$queryString = http_build_query([
    'api_key' => $apiKey,
    'content_type' => 1,
    'format' => 'php_serial',
    'media' => 'photos',
    'method' => 'flickr.photos.search',
    'per_page' => 10,
    'safe_search' => 1,
    'text' => 'Kakadu National Park'
]);
$requestUri = sprintf(
    '%s/rest/?%s',
    BASE_URL,
    $queryString
);
$fp = fopen($requestUri, 'r');

$photoData = unserialize(stream_get_contents($fp));

foreach ($photoData['photos']['photo'] as $photoDatum) {
    printf("Downloading %s.jpg\n", $photoDatum['title']);
    $photoFile = file_get_contents(
        sprintf(
            PHOTO_URL,
            $photoDatum['server'],
            $photoDatum['id'],
            $photoDatum['secret']
        )
    );
    file_put_contents(PHOTOS_DIR . '/' . $photoDatum['title'] . '.jpg', $photoFile);
    printf("  Downloaded %s.jpg\n", $photoDatum['title']);
}

fclose($fp);
8 của đối tượng, với ba tham số được truyền cho lệnh gọi

  • Phương thức HTTP để sử dụng (GET)
  • Đường dẫn của yêu cầu (
    load();
    
    const BASE_URL = 'https://api.flickr.com/services';
    const PHOTO_URL = 'https://live.staticflickr.com/%s/%s_%s_b.jpg';
    const PHOTOS_DIR = 'photos';
    
    $apiKey=$_ENV['API_KEY'];
    
    $opts = [
        'https' => [
            'max_redirects' => 3,
        ],
    ];
    $queryString = http_build_query([
        'api_key' => $apiKey,
        'content_type' => 1,
        'format' => 'php_serial',
        'media' => 'photos',
        'method' => 'flickr.photos.search',
        'per_page' => 10,
        'safe_search' => 1,
        'text' => 'Kakadu National Park'
    ]);
    $requestUri = sprintf(
        '%s/rest/?%s',
        BASE_URL,
        $queryString
    );
    $fp = fopen($requestUri, 'r');
    
    $photoData = unserialize(stream_get_contents($fp));
    
    foreach ($photoData['photos']['photo'] as $photoDatum) {
        printf("Downloading %s.jpg\n", $photoDatum['title']);
        $photoFile = file_get_contents(
            sprintf(
                PHOTO_URL,
                $photoDatum['server'],
                $photoDatum['id'],
                $photoDatum['secret']
            )
        );
        file_put_contents(PHOTOS_DIR . '/' . $photoDatum['title'] . '.jpg', $photoFile);
        printf("  Downloaded %s.jpg\n", $photoDatum['title']);
    }
    
    fclose($fp);
    
    9)
  • Một mảng kết hợp của dữ liệu yêu cầu (_______60)

Sau đó, các kết quả cho yêu cầu được truy xuất và hủy xác thực thành một biểu diễn đối tượng PHP bằng cách chuyển kết quả của

php http-stream.php
1 tới hàm unserialize của PHP;

Sau đó, hình ảnh được tải xuống thư mục ảnh. Nó khá giống với ví dụ về trình bao bọc luồng, tuy nhiên, có một điểm khác biệt chính. Thay vì sử dụng kết hợp

php http-stream.php
2 và
php http-stream.php
3, Guzzle có thể tải xuống tệp bằng một lệnh gọi tới
php http-stream.php
4 vì mảng được cung cấp làm tham số thứ hai cho lệnh gọi

Tùy chọn

php http-stream.php
5 của mảng hướng dẫn Guzzle viết nội dung phản hồi trong tệp được chỉ định trong giá trị của
php http-stream.php
5. Nếu
php http-stream.php
5 không được cung cấp, phản hồi sẽ được lưu trữ trong một tệp tạm thời bằng cách sử dụng trình bao bọc luồng
php http-stream.php
8 của PHP

Ví dụ này cho thấy nơi một thư viện tùy chỉnh có thể tỏa sáng trên chức năng gốc của PHP. Nó có các lớp, phương thức và tham số phương thức hợp lý, trực quan và được thiết kế đặc biệt để thực hiện các yêu cầu HTTP/S;

Mặc dù dài hơn các ví dụ trước, tôi thường thấy thoải mái hơn khi sử dụng Guzzle hơn là sử dụng các luồng PHP hoặc tiện ích mở rộng cURL

Cuối cùng, đây là hai điểm thưởng cuối cùng về Guzzle

  • Nó triển khai cả PSR-7 (giao diện tin nhắn HTTP) và PSR-18 (Máy khách HTTP), làm cho nó có thể tương tác với mã và khung sử dụng các tiêu chuẩn đó
  • Thư viện là tài liệu độc đáo. Tài liệu tốt thường làm cho thư viện trở nên thú vị khi sử dụng

Ghi chú. Đảm bảo rằng bạn kiểm tra xem mã có hoạt động không

Httpful

Tiếp theo, chúng ta hãy xem Httpful. Trích dẫn tài liệu

Httpful là một thư viện PHP đơn giản, có thể xâu chuỗi, có thể đọc được nhằm giúp việc nói HTTP trở nên lành mạnh. Nó cho phép nhà phát triển tập trung vào việc tương tác với các API thay vì sàng lọc qua các trang set_opt cuộn tròn và là ứng dụng khách PHP REST lý tưởng

Đây là một đoạn trích hay từ lớp

php http-stream.php
9 của nó để củng cố câu trích dẫn

Có một sự nhấn mạnh về khả năng đọc mà không làm mất cú pháp ngắn gọn

Để cài đặt thư viện, hãy chạy lệnh bên dưới

API_KEY=
0

Sau đó, tạo một tệp mới trong thư mục dự án có tên là httpful. php và sao chép mã dưới đây vào nó

API_KEY=
1

Ghi chú. Cũng như các ví dụ khác, tôi đã bỏ qua mã chung cho các ví dụ trước đó

Mã bắt đầu bằng cách xây dựng chuỗi truy vấn bằng cách sử dụng

API_KEY=
6. Điều này sau đó được nối với hằng số
Downloading Happy Snappy.jpg
  Downloaded Happy Snappy.jpg
Downloading Miyumba (Riversleigh World Heritage Area, North West Queensland).jpg
  Downloaded Miyumba (Riversleigh World Heritage Area, North West Queensland).jpg
Downloading Riversleigh Fossil Exploration: Site D (Riversleigh World Heritage Area, North West Queensland).jpg
  Downloaded Riversleigh Fossil Exploration: Site D (Riversleigh World Heritage Area, North West Queensland).jpg
Downloading Miyumba (Riversleigh World Heritage Area, North West Queensland).jpg
  Downloaded Miyumba (Riversleigh World Heritage Area, North West Queensland).jpg
Downloading Black-tailed Treecreeper (Climacteris melanurus melanurus).jpg
  Downloaded Black-tailed Treecreeper (Climacteris melanurus melanurus).jpg
Downloading Wilkins' Rock-Wallaby (Petrogale wilkinsi).jpg
  Downloaded Wilkins' Rock-Wallaby (Petrogale wilkinsi).jpg
Downloading Red-tailed Black Cockatoo.jpg
  Downloaded Red-tailed Black Cockatoo.jpg
Downloading 790515Tu-AyersRock-OU34a-bus-RSmith-ss.jpg
  Downloaded 790515Tu-AyersRock-OU34a-bus-RSmith-ss.jpg
Downloading Spotted Nightjar (Eurostopodus argus).jpg
  Downloaded Spotted Nightjar (Eurostopodus argus).jpg
Downloading Chestnut-quilled Rock Pigeon (Petrophassa rufipennis).jpg
  Downloaded Chestnut-quilled Rock Pigeon (Petrophassa rufipennis).jpg
1 để tạo URL yêu cầu gửi tới Flickr. Sau đó, URL được chuyển đến lệnh gọi tĩnh tới phương thức
Downloading Happy Snappy.jpg
  Downloaded Happy Snappy.jpg
Downloading Miyumba (Riversleigh World Heritage Area, North West Queensland).jpg
  Downloaded Miyumba (Riversleigh World Heritage Area, North West Queensland).jpg
Downloading Riversleigh Fossil Exploration: Site D (Riversleigh World Heritage Area, North West Queensland).jpg
  Downloaded Riversleigh Fossil Exploration: Site D (Riversleigh World Heritage Area, North West Queensland).jpg
Downloading Miyumba (Riversleigh World Heritage Area, North West Queensland).jpg
  Downloaded Miyumba (Riversleigh World Heritage Area, North West Queensland).jpg
Downloading Black-tailed Treecreeper (Climacteris melanurus melanurus).jpg
  Downloaded Black-tailed Treecreeper (Climacteris melanurus melanurus).jpg
Downloading Wilkins' Rock-Wallaby (Petrogale wilkinsi).jpg
  Downloaded Wilkins' Rock-Wallaby (Petrogale wilkinsi).jpg
Downloading Red-tailed Black Cockatoo.jpg
  Downloaded Red-tailed Black Cockatoo.jpg
Downloading 790515Tu-AyersRock-OU34a-bus-RSmith-ss.jpg
  Downloaded 790515Tu-AyersRock-OU34a-bus-RSmith-ss.jpg
Downloading Spotted Nightjar (Eurostopodus argus).jpg
  Downloaded Spotted Nightjar (Eurostopodus argus).jpg
Downloading Chestnut-quilled Rock Pigeon (Petrophassa rufipennis).jpg
  Downloaded Chestnut-quilled Rock Pigeon (Petrophassa rufipennis).jpg
3 của
php http-stream.php
9 để thực hiện yêu cầu GET tới API của Flickr

php http-stream.php
9 là lớp mà qua đó các yêu cầu được thực hiện với thư viện. Nó hỗ trợ một số phương pháp để tạo chúng, bao gồm
Downloading Happy Snappy.jpg
  Downloaded Happy Snappy.jpg
Downloading Miyumba (Riversleigh World Heritage Area, North West Queensland).jpg
  Downloaded Miyumba (Riversleigh World Heritage Area, North West Queensland).jpg
Downloading Riversleigh Fossil Exploration: Site D (Riversleigh World Heritage Area, North West Queensland).jpg
  Downloaded Riversleigh Fossil Exploration: Site D (Riversleigh World Heritage Area, North West Queensland).jpg
Downloading Miyumba (Riversleigh World Heritage Area, North West Queensland).jpg
  Downloaded Miyumba (Riversleigh World Heritage Area, North West Queensland).jpg
Downloading Black-tailed Treecreeper (Climacteris melanurus melanurus).jpg
  Downloaded Black-tailed Treecreeper (Climacteris melanurus melanurus).jpg
Downloading Wilkins' Rock-Wallaby (Petrogale wilkinsi).jpg
  Downloaded Wilkins' Rock-Wallaby (Petrogale wilkinsi).jpg
Downloading Red-tailed Black Cockatoo.jpg
  Downloaded Red-tailed Black Cockatoo.jpg
Downloading 790515Tu-AyersRock-OU34a-bus-RSmith-ss.jpg
  Downloaded 790515Tu-AyersRock-OU34a-bus-RSmith-ss.jpg
Downloading Spotted Nightjar (Eurostopodus argus).jpg
  Downloaded Spotted Nightjar (Eurostopodus argus).jpg
Downloading Chestnut-quilled Rock Pigeon (Petrophassa rufipennis).jpg
  Downloaded Chestnut-quilled Rock Pigeon (Petrophassa rufipennis).jpg
5,
Downloading Happy Snappy.jpg
  Downloaded Happy Snappy.jpg
Downloading Miyumba (Riversleigh World Heritage Area, North West Queensland).jpg
  Downloaded Miyumba (Riversleigh World Heritage Area, North West Queensland).jpg
Downloading Riversleigh Fossil Exploration: Site D (Riversleigh World Heritage Area, North West Queensland).jpg
  Downloaded Riversleigh Fossil Exploration: Site D (Riversleigh World Heritage Area, North West Queensland).jpg
Downloading Miyumba (Riversleigh World Heritage Area, North West Queensland).jpg
  Downloaded Miyumba (Riversleigh World Heritage Area, North West Queensland).jpg
Downloading Black-tailed Treecreeper (Climacteris melanurus melanurus).jpg
  Downloaded Black-tailed Treecreeper (Climacteris melanurus melanurus).jpg
Downloading Wilkins' Rock-Wallaby (Petrogale wilkinsi).jpg
  Downloaded Wilkins' Rock-Wallaby (Petrogale wilkinsi).jpg
Downloading Red-tailed Black Cockatoo.jpg
  Downloaded Red-tailed Black Cockatoo.jpg
Downloading 790515Tu-AyersRock-OU34a-bus-RSmith-ss.jpg
  Downloaded 790515Tu-AyersRock-OU34a-bus-RSmith-ss.jpg
Downloading Spotted Nightjar (Eurostopodus argus).jpg
  Downloaded Spotted Nightjar (Eurostopodus argus).jpg
Downloading Chestnut-quilled Rock Pigeon (Petrophassa rufipennis).jpg
  Downloaded Chestnut-quilled Rock Pigeon (Petrophassa rufipennis).jpg
6,
Downloading Happy Snappy.jpg
  Downloaded Happy Snappy.jpg
Downloading Miyumba (Riversleigh World Heritage Area, North West Queensland).jpg
  Downloaded Miyumba (Riversleigh World Heritage Area, North West Queensland).jpg
Downloading Riversleigh Fossil Exploration: Site D (Riversleigh World Heritage Area, North West Queensland).jpg
  Downloaded Riversleigh Fossil Exploration: Site D (Riversleigh World Heritage Area, North West Queensland).jpg
Downloading Miyumba (Riversleigh World Heritage Area, North West Queensland).jpg
  Downloaded Miyumba (Riversleigh World Heritage Area, North West Queensland).jpg
Downloading Black-tailed Treecreeper (Climacteris melanurus melanurus).jpg
  Downloaded Black-tailed Treecreeper (Climacteris melanurus melanurus).jpg
Downloading Wilkins' Rock-Wallaby (Petrogale wilkinsi).jpg
  Downloaded Wilkins' Rock-Wallaby (Petrogale wilkinsi).jpg
Downloading Red-tailed Black Cockatoo.jpg
  Downloaded Red-tailed Black Cockatoo.jpg
Downloading 790515Tu-AyersRock-OU34a-bus-RSmith-ss.jpg
  Downloaded 790515Tu-AyersRock-OU34a-bus-RSmith-ss.jpg
Downloading Spotted Nightjar (Eurostopodus argus).jpg
  Downloaded Spotted Nightjar (Eurostopodus argus).jpg
Downloading Chestnut-quilled Rock Pigeon (Petrophassa rufipennis).jpg
  Downloaded Chestnut-quilled Rock Pigeon (Petrophassa rufipennis).jpg
7,
Downloading Happy Snappy.jpg
  Downloaded Happy Snappy.jpg
Downloading Miyumba (Riversleigh World Heritage Area, North West Queensland).jpg
  Downloaded Miyumba (Riversleigh World Heritage Area, North West Queensland).jpg
Downloading Riversleigh Fossil Exploration: Site D (Riversleigh World Heritage Area, North West Queensland).jpg
  Downloaded Riversleigh Fossil Exploration: Site D (Riversleigh World Heritage Area, North West Queensland).jpg
Downloading Miyumba (Riversleigh World Heritage Area, North West Queensland).jpg
  Downloaded Miyumba (Riversleigh World Heritage Area, North West Queensland).jpg
Downloading Black-tailed Treecreeper (Climacteris melanurus melanurus).jpg
  Downloaded Black-tailed Treecreeper (Climacteris melanurus melanurus).jpg
Downloading Wilkins' Rock-Wallaby (Petrogale wilkinsi).jpg
  Downloaded Wilkins' Rock-Wallaby (Petrogale wilkinsi).jpg
Downloading Red-tailed Black Cockatoo.jpg
  Downloaded Red-tailed Black Cockatoo.jpg
Downloading 790515Tu-AyersRock-OU34a-bus-RSmith-ss.jpg
  Downloaded 790515Tu-AyersRock-OU34a-bus-RSmith-ss.jpg
Downloading Spotted Nightjar (Eurostopodus argus).jpg
  Downloaded Spotted Nightjar (Eurostopodus argus).jpg
Downloading Chestnut-quilled Rock Pigeon (Petrophassa rufipennis).jpg
  Downloaded Chestnut-quilled Rock Pigeon (Petrophassa rufipennis).jpg
8 và
Downloading Happy Snappy.jpg
  Downloaded Happy Snappy.jpg
Downloading Miyumba (Riversleigh World Heritage Area, North West Queensland).jpg
  Downloaded Miyumba (Riversleigh World Heritage Area, North West Queensland).jpg
Downloading Riversleigh Fossil Exploration: Site D (Riversleigh World Heritage Area, North West Queensland).jpg
  Downloaded Riversleigh Fossil Exploration: Site D (Riversleigh World Heritage Area, North West Queensland).jpg
Downloading Miyumba (Riversleigh World Heritage Area, North West Queensland).jpg
  Downloaded Miyumba (Riversleigh World Heritage Area, North West Queensland).jpg
Downloading Black-tailed Treecreeper (Climacteris melanurus melanurus).jpg
  Downloaded Black-tailed Treecreeper (Climacteris melanurus melanurus).jpg
Downloading Wilkins' Rock-Wallaby (Petrogale wilkinsi).jpg
  Downloaded Wilkins' Rock-Wallaby (Petrogale wilkinsi).jpg
Downloading Red-tailed Black Cockatoo.jpg
  Downloaded Red-tailed Black Cockatoo.jpg
Downloading 790515Tu-AyersRock-OU34a-bus-RSmith-ss.jpg
  Downloaded 790515Tu-AyersRock-OU34a-bus-RSmith-ss.jpg
Downloading Spotted Nightjar (Eurostopodus argus).jpg
  Downloaded Spotted Nightjar (Eurostopodus argus).jpg
Downloading Chestnut-quilled Rock Pigeon (Petrophassa rufipennis).jpg
  Downloaded Chestnut-quilled Rock Pigeon (Petrophassa rufipennis).jpg
9, ngoài ra còn có
Downloading Happy Snappy.jpg
  Downloaded Happy Snappy.jpg
Downloading Miyumba (Riversleigh World Heritage Area, North West Queensland).jpg
  Downloaded Miyumba (Riversleigh World Heritage Area, North West Queensland).jpg
Downloading Riversleigh Fossil Exploration: Site D (Riversleigh World Heritage Area, North West Queensland).jpg
  Downloaded Riversleigh Fossil Exploration: Site D (Riversleigh World Heritage Area, North West Queensland).jpg
Downloading Miyumba (Riversleigh World Heritage Area, North West Queensland).jpg
  Downloaded Miyumba (Riversleigh World Heritage Area, North West Queensland).jpg
Downloading Black-tailed Treecreeper (Climacteris melanurus melanurus).jpg
  Downloaded Black-tailed Treecreeper (Climacteris melanurus melanurus).jpg
Downloading Wilkins' Rock-Wallaby (Petrogale wilkinsi).jpg
  Downloaded Wilkins' Rock-Wallaby (Petrogale wilkinsi).jpg
Downloading Red-tailed Black Cockatoo.jpg
  Downloaded Red-tailed Black Cockatoo.jpg
Downloading 790515Tu-AyersRock-OU34a-bus-RSmith-ss.jpg
  Downloaded 790515Tu-AyersRock-OU34a-bus-RSmith-ss.jpg
Downloading Spotted Nightjar (Eurostopodus argus).jpg
  Downloaded Spotted Nightjar (Eurostopodus argus).jpg
Downloading Chestnut-quilled Rock Pigeon (Petrophassa rufipennis).jpg
  Downloaded Chestnut-quilled Rock Pigeon (Petrophassa rufipennis).jpg
3

Nó cũng bao gồm nhiều phương pháp hỗ trợ khác, bao gồm

  • php --ri curl | grep "cURL support => enabled"
    
    1 để đính kèm tệp
  • php --ri curl | grep "cURL support => enabled"
    
    2 để thêm tiêu đề vào yêu cầu
  • php --ri curl | grep "cURL support => enabled"
    
    3/
    php --ri curl | grep "cURL support => enabled"
    
    4 để xác thực
  • php --ri curl | grep "cURL support => enabled"
    
    5 để đặt Loại nội dung và tiêu đề dự kiến
  • php --ri curl | grep "cURL support => enabled"
    
    6 cho các yêu cầu chuyển hướng sau

Như với các ví dụ trước, phần thân của phản hồi (

php --ri curl | grep "cURL support => enabled"
7) sau đó đã được hủy xác thực thành một đối tượng PHP cũ đơn giản, nếu phần thân có sẵn

Mã để tải xuống hình ảnh khá giống với các ví dụ trước, sử dụng

php http-stream.php
3 để ghi các tệp vào hệ thống tệp cục bộ, vì thư viện không cung cấp phương thức để thực hiện điều đó

Httpful có lẽ là cách sử dụng đơn giản nhất trong ba thư viện. Nó có một chút điểm chung với GuzzleHttp, nhưng nó cũng làm mọi thứ theo cách riêng của nó. Nó không chuyển đổi một mảng kết hợp thành một chuỗi truy vấn, điều mà tôi rất thích, nhưng các phương thức mà nó hỗ trợ đều trực quan và logic, đồng thời giao diện trôi chảy giúp việc xây dựng và gửi yêu cầu trở nên nhanh chóng và dễ dàng

Một điểm cuối cùng đáng lưu ý. thư viện dựa trên phần mở rộng cURL của PHP. Điều này củng cố thêm mức độ đáng tin cậy của tiện ích mở rộng cURL và cách bạn có thể xây dựng dựa trên nó để tạo ra công cụ mạnh mẽ và biểu cảm hơn

Ghi chú. Đảm bảo rằng bạn kiểm tra xem mã có hoạt động không

Máy khách HTTP của Symfony

Cuối cùng, hãy hoàn thiện bài viết bằng cách xem ứng dụng khách HTTP của Symfony. Trích dẫn tài liệu

Thành phần HttpClient là ứng dụng khách HTTP cấp thấp có hỗ trợ cho cả trình bao bọc luồng PHP và cURL. Nó cung cấp các tiện ích để sử dụng API và hỗ trợ các hoạt động đồng bộ và không đồng bộ

Để cài đặt nó, hãy chạy lệnh bên dưới

API_KEY=
2

Sau đó, tạo một tệp mới trong thư mục dự án có tên là symfony. php và sao chép mã dưới đây vào nó

API_KEY=
3

Mã bắt đầu, tương tự như ví dụ GuzzleHttp, bằng cách xác định một mảng dữ liệu yêu cầu kết hợp. Như trước đây, nó định nghĩa

load();

const BASE_URL = 'https://api.flickr.com/services';
const PHOTO_URL = 'https://live.staticflickr.com/%s/%s_%s_b.jpg';
const PHOTOS_DIR = 'photos';

$apiKey=$_ENV['API_KEY'];

$opts = [
    'https' => [
        'max_redirects' => 3,
    ],
];
$queryString = http_build_query([
    'api_key' => $apiKey,
    'content_type' => 1,
    'format' => 'php_serial',
    'media' => 'photos',
    'method' => 'flickr.photos.search',
    'per_page' => 10,
    'safe_search' => 1,
    'text' => 'Kakadu National Park'
]);
$requestUri = sprintf(
    '%s/rest/?%s',
    BASE_URL,
    $queryString
);
$fp = fopen($requestUri, 'r');

$photoData = unserialize(stream_get_contents($fp));

foreach ($photoData['photos']['photo'] as $photoDatum) {
    printf("Downloading %s.jpg\n", $photoDatum['title']);
    $photoFile = file_get_contents(
        sprintf(
            PHOTO_URL,
            $photoDatum['server'],
            $photoDatum['id'],
            $photoDatum['secret']
        )
    );
    file_put_contents(PHOTOS_DIR . '/' . $photoDatum['title'] . '.jpg', $photoFile);
    printf("  Downloaded %s.jpg\n", $photoDatum['title']);
}

fclose($fp);
3 để bật chế độ gỡ lỗi và
load();

const BASE_URL = 'https://api.flickr.com/services';
const PHOTO_URL = 'https://live.staticflickr.com/%s/%s_%s_b.jpg';
const PHOTOS_DIR = 'photos';

$apiKey=$_ENV['API_KEY'];

$opts = [
    'https' => [
        'max_redirects' => 3,
    ],
];
$queryString = http_build_query([
    'api_key' => $apiKey,
    'content_type' => 1,
    'format' => 'php_serial',
    'media' => 'photos',
    'method' => 'flickr.photos.search',
    'per_page' => 10,
    'safe_search' => 1,
    'text' => 'Kakadu National Park'
]);
$requestUri = sprintf(
    '%s/rest/?%s',
    BASE_URL,
    $queryString
);
$fp = fopen($requestUri, 'r');

$photoData = unserialize(stream_get_contents($fp));

foreach ($photoData['photos']['photo'] as $photoDatum) {
    printf("Downloading %s.jpg\n", $photoDatum['title']);
    $photoFile = file_get_contents(
        sprintf(
            PHOTO_URL,
            $photoDatum['server'],
            $photoDatum['id'],
            $photoDatum['secret']
        )
    );
    file_put_contents(PHOTOS_DIR . '/' . $photoDatum['title'] . '.jpg', $photoFile);
    printf("  Downloaded %s.jpg\n", $photoDatum['title']);
}

fclose($fp);
4 để tạo chuỗi truy vấn từ

Sau đó, nó gọi phương thức tĩnh

load();

// .. constants, the call to http_build_query, and definition of $requestUri, and $queryString

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $requestUri);
curl_setopt($ch, CURLOPT_SSH_COMPRESSION, true);
curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_URL => $requestUri
]);
$result = curl_exec($ch);
$photoData = unserialize($result);

curl_close($ch);

foreach ($photoData['photos']['photo'] as $photoDatum) {
    printf("Downloading %s.jpg\n", $photoDatum['title']);
    $file_url = sprintf(
        PHOTO_URL,
        $photoDatum['server'],
        $photoDatum['id'],
        $photoDatum['secret']
    );
    $destination_path = PHOTOS_DIR . '/' . $photoDatum['title'] . '.jpg';

    $fp = fopen($destination_path, "w");
    $ch = curl_init($file_url);
    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_exec($ch);
    $st_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    fclose($fp);
    printf("  Downloaded %s.jpg\n", $photoDatum['title']);
}
2 của
load();

// .. constants, the call to http_build_query, and definition of $requestUri, and $queryString

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $requestUri);
curl_setopt($ch, CURLOPT_SSH_COMPRESSION, true);
curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_URL => $requestUri
]);
$result = curl_exec($ch);
$photoData = unserialize($result);

curl_close($ch);

foreach ($photoData['photos']['photo'] as $photoDatum) {
    printf("Downloading %s.jpg\n", $photoDatum['title']);
    $file_url = sprintf(
        PHOTO_URL,
        $photoDatum['server'],
        $photoDatum['id'],
        $photoDatum['secret']
    );
    $destination_path = PHOTOS_DIR . '/' . $photoDatum['title'] . '.jpg';

    $fp = fopen($destination_path, "w");
    $ch = curl_init($file_url);
    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_exec($ch);
    $st_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    fclose($fp);
    printf("  Downloaded %s.jpg\n", $photoDatum['title']);
}
1 để khởi tạo một ứng dụng khách HTTP để thực hiện các yêu cầu, chuyển cho nó một số tùy chọn yêu cầu mặc định, những tùy chọn này sẽ được sử dụng cho tất cả các yêu cầu

Sau đó, phương thức

load();

const BASE_URL = 'https://api.flickr.com/services';
const PHOTO_URL = 'https://live.staticflickr.com/%s/%s_%s_b.jpg';
const PHOTOS_DIR = 'photos';

$apiKey=$_ENV['API_KEY'];

$opts = [
    'https' => [
        'max_redirects' => 3,
    ],
];
$queryString = http_build_query([
    'api_key' => $apiKey,
    'content_type' => 1,
    'format' => 'php_serial',
    'media' => 'photos',
    'method' => 'flickr.photos.search',
    'per_page' => 10,
    'safe_search' => 1,
    'text' => 'Kakadu National Park'
]);
$requestUri = sprintf(
    '%s/rest/?%s',
    BASE_URL,
    $queryString
);
$fp = fopen($requestUri, 'r');

$photoData = unserialize(stream_get_contents($fp));

foreach ($photoData['photos']['photo'] as $photoDatum) {
    printf("Downloading %s.jpg\n", $photoDatum['title']);
    $photoFile = file_get_contents(
        sprintf(
            PHOTO_URL,
            $photoDatum['server'],
            $photoDatum['id'],
            $photoDatum['secret']
        )
    );
    file_put_contents(PHOTOS_DIR . '/' . $photoDatum['title'] . '.jpg', $photoFile);
    printf("  Downloaded %s.jpg\n", $photoDatum['title']);
}

fclose($fp);
8 của
load();

// .. constants, the call to http_build_query, and definition of $requestUri, and $queryString

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $requestUri);
curl_setopt($ch, CURLOPT_SSH_COMPRESSION, true);
curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_URL => $requestUri
]);
$result = curl_exec($ch);
$photoData = unserialize($result);

curl_close($ch);

foreach ($photoData['photos']['photo'] as $photoDatum) {
    printf("Downloading %s.jpg\n", $photoDatum['title']);
    $file_url = sprintf(
        PHOTO_URL,
        $photoDatum['server'],
        $photoDatum['id'],
        $photoDatum['secret']
    );
    $destination_path = PHOTOS_DIR . '/' . $photoDatum['title'] . '.jpg';

    $fp = fopen($destination_path, "w");
    $ch = curl_init($file_url);
    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_exec($ch);
    $st_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    fclose($fp);
    printf("  Downloaded %s.jpg\n", $photoDatum['title']);
}
3 được gọi để thực hiện yêu cầu, trong đó phương thức HTTP,
load();

// .. constants, the call to http_build_query, and definition of $requestUri, and $queryString

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $requestUri);
curl_setopt($ch, CURLOPT_SSH_COMPRESSION, true);
curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_URL => $requestUri
]);
$result = curl_exec($ch);
$photoData = unserialize($result);

curl_close($ch);

foreach ($photoData['photos']['photo'] as $photoDatum) {
    printf("Downloading %s.jpg\n", $photoDatum['title']);
    $file_url = sprintf(
        PHOTO_URL,
        $photoDatum['server'],
        $photoDatum['id'],
        $photoDatum['secret']
    );
    $destination_path = PHOTOS_DIR . '/' . $photoDatum['title'] . '.jpg';

    $fp = fopen($destination_path, "w");
    $ch = curl_init($file_url);
    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_exec($ch);
    $st_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    fclose($fp);
    printf("  Downloaded %s.jpg\n", $photoDatum['title']);
}
5, URL yêu cầu cơ sở,
Downloading Happy Snappy.jpg
  Downloaded Happy Snappy.jpg
Downloading Miyumba (Riversleigh World Heritage Area, North West Queensland).jpg
  Downloaded Miyumba (Riversleigh World Heritage Area, North West Queensland).jpg
Downloading Riversleigh Fossil Exploration: Site D (Riversleigh World Heritage Area, North West Queensland).jpg
  Downloaded Riversleigh Fossil Exploration: Site D (Riversleigh World Heritage Area, North West Queensland).jpg
Downloading Miyumba (Riversleigh World Heritage Area, North West Queensland).jpg
  Downloaded Miyumba (Riversleigh World Heritage Area, North West Queensland).jpg
Downloading Black-tailed Treecreeper (Climacteris melanurus melanurus).jpg
  Downloaded Black-tailed Treecreeper (Climacteris melanurus melanurus).jpg
Downloading Wilkins' Rock-Wallaby (Petrogale wilkinsi).jpg
  Downloaded Wilkins' Rock-Wallaby (Petrogale wilkinsi).jpg
Downloading Red-tailed Black Cockatoo.jpg
  Downloaded Red-tailed Black Cockatoo.jpg
Downloading 790515Tu-AyersRock-OU34a-bus-RSmith-ss.jpg
  Downloaded 790515Tu-AyersRock-OU34a-bus-RSmith-ss.jpg
Downloading Spotted Nightjar (Eurostopodus argus).jpg
  Downloaded Spotted Nightjar (Eurostopodus argus).jpg
Downloading Chestnut-quilled Rock Pigeon (Petrophassa rufipennis).jpg
  Downloaded Chestnut-quilled Rock Pigeon (Petrophassa rufipennis).jpg
1 và dữ liệu truy vấn được cung cấp, với phản hồi được lưu trữ trong
load();

// .. constants, the call to http_build_query, and definition of $requestUri, and $queryString

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $requestUri);
curl_setopt($ch, CURLOPT_SSH_COMPRESSION, true);
curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_URL => $requestUri
]);
$result = curl_exec($ch);
$photoData = unserialize($result);

curl_close($ch);

foreach ($photoData['photos']['photo'] as $photoDatum) {
    printf("Downloading %s.jpg\n", $photoDatum['title']);
    $file_url = sprintf(
        PHOTO_URL,
        $photoDatum['server'],
        $photoDatum['id'],
        $photoDatum['secret']
    );
    $destination_path = PHOTOS_DIR . '/' . $photoDatum['title'] . '.jpg';

    $fp = fopen($destination_path, "w");
    $ch = curl_init($file_url);
    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_exec($ch);
    $st_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    fclose($fp);
    printf("  Downloaded %s.jpg\n", $photoDatum['title']);
}
7

Ở đây, chúng ta khác một chút so với các ví dụ trước bằng cách trước tiên truy xuất mã trạng thái của phản hồi (

load();

// .. constants, the call to http_build_query, and definition of $requestUri, and $queryString

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $requestUri);
curl_setopt($ch, CURLOPT_SSH_COMPRESSION, true);
curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_URL => $requestUri
]);
$result = curl_exec($ch);
$photoData = unserialize($result);

curl_close($ch);

foreach ($photoData['photos']['photo'] as $photoDatum) {
    printf("Downloading %s.jpg\n", $photoDatum['title']);
    $file_url = sprintf(
        PHOTO_URL,
        $photoDatum['server'],
        $photoDatum['id'],
        $photoDatum['secret']
    );
    $destination_path = PHOTOS_DIR . '/' . $photoDatum['title'] . '.jpg';

    $fp = fopen($destination_path, "w");
    $ch = curl_init($file_url);
    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_exec($ch);
    $st_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    fclose($fp);
    printf("  Downloaded %s.jpg\n", $photoDatum['title']);
}
8) và tiêu đề kiểu nội dung (
load();

// .. constants, the call to http_build_query, and definition of $requestUri, and $queryString

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $requestUri);
curl_setopt($ch, CURLOPT_SSH_COMPRESSION, true);
curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_URL => $requestUri
]);
$result = curl_exec($ch);
$photoData = unserialize($result);

curl_close($ch);

foreach ($photoData['photos']['photo'] as $photoDatum) {
    printf("Downloading %s.jpg\n", $photoDatum['title']);
    $file_url = sprintf(
        PHOTO_URL,
        $photoDatum['server'],
        $photoDatum['id'],
        $photoDatum['secret']
    );
    $destination_path = PHOTOS_DIR . '/' . $photoDatum['title'] . '.jpg';

    $fp = fopen($destination_path, "w");
    $ch = curl_init($file_url);
    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_exec($ch);
    $st_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    fclose($fp);
    printf("  Downloaded %s.jpg\n", $photoDatum['title']);
}
9), trước khi truy xuất và hủy đánh số thứ tự nội dung phản hồi thành một đối tượng PHP cũ đơn giản (
API_KEY=
40)

Sau đó, cách các hình ảnh được tải xuống, một lần nữa, phần lớn tương tự như các ví dụ trước đó. Như với ví dụ về Httpful, nó sử dụng

php http-stream.php
3 để ghi các tệp vào hệ thống tệp cục bộ, vì không có phương thức nào trong thư viện làm việc đó cho chúng tôi

Sau một thời gian sử dụng, tôi thấy ứng dụng khách HTTP của Symfony có thể so sánh với GuzzleHttp về chức năng, tính biểu cảm và tính trực giác. Tên lớp, phương thức và tham số có ý nghĩa và thư viện dễ sử dụng, e. g. , nó đơn giản hóa việc tạo một chuỗi truy vấn từ một mảng kết hợp. Do đó, nó đơn giản hóa rất nhiều nỗ lực cần thiết trong việc thực hiện các yêu cầu HTTP/S

Ghi chú. Đảm bảo rằng bạn kiểm tra xem mã có hoạt động không

Đó là 5 cách để thực hiện yêu cầu HTTP trong PHP

Chúng tôi đã xem xét cách tạo chúng bằng cách sử dụng trình bao bọc luồng HTTP/S của PHP, tiện ích mở rộng cURL của PHP, GuzzleHttp, Httpful và ứng dụng khách HTTP Symfony. Ngoài một ví dụ sử dụng khá đơn giản cho từng phương pháp, chúng tôi đã xem xét ngắn gọn một số ưu điểm của từng phương pháp

Mặc dù mỗi tùy chọn trong số 5 tùy chọn được đề cập ở đây đều có thể được sử dụng trong bất kỳ dự án nào, nhưng theo kinh nghiệm, dự án của bạn càng lớn và phức tạp thì bạn càng có thể được phục vụ tốt hơn bằng cách sử dụng một trong các gói của bên thứ ba. Nếu vậy, đề xuất của tôi là GuzzleHttp

Trong những trường hợp này, các gói của bên thứ ba có thể sẽ cải thiện cả hiệu quả và sự thích thú, giúp nhà phát triển tiết kiệm được đáng kể thời gian. Điều đó nói rằng, trong khi không muốn nói chuyện với họ, tiện ích mở rộng cURL của PHP hoặc trình bao bọc luồng HTTP/S có thể là tất cả những gì bạn cần. Đôi khi ít lại hơn

Một điều cuối cùng. cảm ơn tất cả những người đã cung cấp phản hồi cho Tweet của tôi khi tôi đang nghiên cứu bài viết này. Nó đã giúp tôi rất nhiều trong cả việc viết và trau chuốt nó

hack vui vẻ. Tôi nóng lòng muốn xem những gì bạn xây dựng với họ

Matthew Setter là Trình chỉnh sửa PHP trong nhóm Twilio Voices và (đương nhiên) là nhà phát triển PHP. Ông cũng là tác giả của Mezzio Essentials và Docker Essentials. Khi anh ấy không viết mã PHP, anh ấy đang chỉnh sửa các bài viết PHP tuyệt vời tại Twilio. Bạn có thể tìm thấy anh ấy tại msetter@twilio. com, Twitter và GitHub

Đánh giá bài viết này

1 2 3 4 5

tác giả

  • Cách nhận phản hồi từ api trong php
    Matthew Setter

người phản biện

  • Cách nhận phản hồi từ api trong php
    Miguel Grinberg
  • Cách nhận phản hồi từ api trong php
    Trận chiến Marcus
  • Cách nhận phản hồi từ api trong php
    Matthew Gilliard


bài viết liên quan

Cách nhận phản hồi từ api trong php

Học ngôn ngữ Maasai theo cách thú vị

Ngày 20 tháng 10 năm 2022

Trong hướng dẫn này, bạn sẽ xây dựng một ứng dụng giúp bạn học ngôn ngữ Maasai một cách dễ dàng và thú vị với WhatsApp

Cách nhận phản hồi từ api trong php

Pub/Sub trong Laravel - Hiểu biết sâu sắc

Ngày 20 tháng 10 năm 2022

Trong hướng dẫn này, bạn sẽ tìm hiểu về Pub/Sub, một mẫu thiết kế phần mềm hướng thông báo và cách triển khai nó trong Laravel

Cách nhận phản hồi từ api trong php

Xây dựng trình rút ngắn URL của riêng bạn với PHP và PostgreSQL

Ngày 06 tháng 10 năm 2022

Trong hướng dẫn này, bạn sẽ học cách xây dựng trình rút ngắn URL của riêng mình bằng PHP và PostgreSQL

Cách nhận phản hồi từ api trong php

Phát triển ứng dụng Symfony bằng Svelte và Webpack Encore để quản lý lịch sử tin nhắn Twilio của bạn

Ngày 27 tháng 9 năm 2022

Trong bài viết này, bạn sẽ học cách phát triển ứng dụng với Svelte, Webpack Encore và Symfony có thể tương tác với lịch sử tin nhắn Twilio của bạn

Cách nhận phản hồi từ api trong php

Xây dựng trạm thời tiết của riêng bạn với PHP, Python và Raspberry Pi - Phần II

Ngày 08 tháng 9 năm 2022

Trong phần thứ hai của loạt bài này, bạn sẽ tìm hiểu cách thêm khả năng gửi thông báo tóm tắt hàng ngày qua cả SMS và email bằng API Twilio và SendGrid cho trạm thời tiết dựa trên Raspberry Pi

Cách nhận phản hồi từ api trong php

Tạo một lệnh thủ công để xem các cuộc gọi Twilio

Ngày 23 tháng 8 năm 2022

Trong hướng dẫn này, bạn sẽ tìm hiểu cách tạo lệnh Artisan tùy chỉnh để liệt kê các cuộc gọi thoại bạn đã thực hiện trên tài khoản Twilio của mình

Làm cách nào để lấy dữ liệu từ URL API trong PHP?

php // Bao gồm các lớp Yêu cầu và Phản hồi $url = 'https. //api. exoclick. com/v2/đăng nhập';

Chúng tôi có thể sử dụng API trong PHP không?

Một ứng dụng có thể gọi API chương trình khác để sử dụng một số chức năng . API nhận yêu cầu và trả về kết quả trong hệ thống phần mềm của lập trình viên. Nếu hệ thống giao tiếp với cơ sở dữ liệu, thì các API sẽ được hiển thị bởi các tiện ích mở rộng PHP.

PHP có API REST không?

API REST của PHP . Ăn tham . Một số tính năng của khung API Guzzle giúp nó trở nên hoàn hảo để xây dựng API REST là. Bộ nhớ đệm. API REST cần tính năng này để lưu trữ các yêu cầu máy khách-máy chủ.

API REST trong PHP là gì?

REST (Chuyển giao trạng thái đại diện) là API xác định một tập hợp các chức năng mà lập trình viên có thể sử dụng để gửi yêu cầu và nhận phản hồi bằng các phương thức giao thức HTTP như GET và POST