Hongmu Notes
Home Language Notes When making a PHP API request, use `curl` to receive the response as an array.
Language Notes PHP

When making a PHP API request, use `curl` to receive the response as an array.

When making a PHP API request, use `curl` to receive the response as an array.

This isn't particularly complex code; I previously used `file_get_contents`, but I felt the overall efficiency wasn't very good. I remember having published a similar article before – I must have forgotten about it – so I'll record it again now.

Use the cURL library to send an HTTP request and configure various options:

  • CUR CURLOPT_URL: Set the URL for the request.
  • CUR CURLOPT_TIMEOUT: Sets the request timeout duration in seconds.
  • CUR CURLOPT_RETURNTRANSFER: Returns the result as a string instead of outputting it directly.

The function accepts two parameters:

  • $durl: The requested URL.
  • $cache: Cache duration (in seconds; default is 0, indicating no caching.) (This feature is not yet fully implemented as it uses static web pages.)

The function sends a request using cURL and stores the returned result as a string in the variable $r. Then, it closes the cURL session using `curl_close()` and decodes the returned JSON-formatted data into an associative array using `json_decode()`. Finally, it returns this array.

PHP code

public function get_api($durl,$cache = 0)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $durl);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $r = curl_exec($ch);
        curl_close($ch);
        return json_decode($r,true);
    }

Upgrade and Optimization

function get_api($durl, $cache = 0)
{
    // 初始化cURL会话
    $ch = curl_init();

    // 设置cURL选项
    curl_setopt($ch, CURLOPT_URL, $durl);          // 设置请求的URL
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);          // 设置超时时间为5秒
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);   // 将结果通过变量返回,而不是直接输出

    // 获取Referer的主机部分
    $referer_host = parse_url($durl, PHP_URL_SCHEME) . '://' . parse_url($durl, PHP_URL_HOST);
    curl_setopt($ch, CURLOPT_REFERER, $referer_host);  // 设置Referer头,指定来源主机部分

    // 模拟浏览器访问的相关选项
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.9999.999 Safari/537.36');  // 设置User-Agent头,模拟浏览器
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Accept: application/json',
    'Content-Type: application/json; charset=utf-8'
    ));
    
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

    // 执行请求并获取响应结果
    $r = curl_exec($ch);

    // 关闭cURL会话
    curl_close($ch);

    // 解析JSON格式的响应结果,并返回解析后的数组
    return json_decode($r, true);
}

 

微信赞赏

WeChat

支付宝赞赏

Alipay

✍️ Author: Hong Mu

webmaster · Thanks for reading, stay tuned for more exciting content

Author homepage View home page →

Related articles

PHP ob function record

PHP ob function record Language Notes PHP

Usage of the following three functions ob_get_contents(); ob_end_clean(); ob_start(); You can use these functions to buffer local files and execute local script code. Use ob_start() to save the output code into the buffer, and the page will not be displayed; then use ob_get_contents to get the data in the buffer. o…
👁 141
PHP preg

PHP preg Language Notes PHP

The preg_match_all function is used to perform a global regular expression match. preg_match_all() Syntax int preg_match_all ( string $pattern , string $subject [, array &$matches [, int $flags = PREG…
👁 169
Detailed explanation of PHP ternary operator and if

Detailed explanation of PHP ternary operator and if Language Notes PHP

Ternary operator condition ? Result 1 : Result 2 Explanation: The position in front of the question mark is the condition for judgment. If the condition is met, the result is 1, and if it is not met, the result is 2. This article compares and explains the ternary operator and if...else... in detail. I hope it will be helpful to everyone. Today when I was revising my paper online, I encountered a statement that I couldn’t understand: $if_summary = $row['IF_SUMMARY']=…
👁 189
PHP cast type

PHP cast type Language Notes PHP PHP collection PHP and mysql

Get the data type 1. If you want to check the value and type of an expression, use var_dump(). 2. If you just want to get an easy-to-read type expression for debugging, use gettype(). 3. To check a certain type, do not use gettype(), but use the is_type() function. Converting Strings to Numbers When a string is evaluated as a number, the result is determined according to the following rules...
👁 232

Recommended reading

Responsive outdoor gear and sports equipment website template – 0981

Responsive outdoor gear and sports equipment website template – 0981 Practical Collection Yiyou template

This EyouCMS responsive template is ideal for the outdoor and sports equipment industries. Its dynamic outdoor design style is perfect for showcasing outdoor gear products, sports goods, brand stories, and sports solutions. It helps outdoor sports brands showcase their products online and attract sports enthusiasts. Template Demo | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS...
👁 48
Responsive Early Childhood Education Toy Website Template 0297

Responsive Early Childhood Education Toy Website Template 0297 Practical Collection Yiyou template

This EyouCMS responsive template is ideal for the early childhood education and toy industry. Its vibrant and playful design is perfect for showcasing early education courses, toy products, brand stories, and educational philosophies. It helps early education brands attract parents online and strengthen their brand image. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS (...
👁 45
(Adaptive mobile version) Baidu MIP – PBootCMS template for building decoration and renovation websites; Download source code for wall cladding materials website – 0810

(Adaptive mobile version) Baidu MIP – PBootCMS template for building decoration and renovation websites; Download source code for wall cladding materials website – 0810 Practical Collection pbootcms Template

A Baidu MIP-compliant PbootCMS website template for architectural and interior decoration projects, compatible with both PC and WAP devices. Featuring a professional, modern design style ideal for showcasing curtain wall materials, renovation projects, and decorative case studies. Support for Baidu MIP helps enhance mobile SEO performance and attract more traffic. Template Preview | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5....
👁 61
(Adaptive Mobile Version) Responsive e-Technology Product Company – PBootCMS Website Template; Download E-Product Website Source Code – 0156

(Adaptive Mobile Version) Responsive e-Technology Product Company – PBootCMS Website Template; Download E-Product Website Source Code – 0156 Practical Collection pbootcms Template

An adaptive, mobile-friendly responsive e-tech product company website template – PbootCMS. Its futuristic design is ideal for showcasing smartphones, computer accessories, smart hardware, and other electronic products. This template helps tech brands build a stylish, cutting-edge online brand image and attract younger consumers. Template Overview | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: ww...
👁 55
ChatGPT generates articles in Markdown format.

ChatGPT generates articles in Markdown format. Practical Collection Utility tools

In the early hours of March 2, OpenAI launched the official ChatGPT API – not the underlying GPT-3.5 large-scale model, but the core ChatGPT model itself: ChatGPT-3.5-Turbo! The ChatGPT-3.5-Turbo model is the model used by ChatGPT and represents the fastest, most cost-effective, and most flexible model in the GPT-3.5 series. It can deliver ultra-high...
👁 223
Responsive premium watch and luggage website template – 0982

Responsive premium watch and luggage website template – 0982 Practical Collection Yiyou template

An eYouCMS responsive website template designed for the premium watch and luggage industry. Its sophisticated and trendy design is ideal for showcasing watch products, luggage collections, brand stories, and customisation services. This template helps luxury brands present their products online and attract high-net-worth customers. Template Demo | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for eYouCMS | eYouCMS...
👁 31