代码之家  ›  专栏  ›  技术社区  ›  Michael

PHP cURL HTTP请求

  •  0
  • Michael  · 技术社区  · 2 年前

    我试图使用cURL运行一个PHP HTTP Request for a Framework,并尝试使用可读文档运行代码,但出现了两个错误,所有错误都加入了;致命错误:未捕获错误:在C:\examplep\htdocs\Raspberry\requests.php:18堆栈跟踪:#0 C:\examplep\tdocs\Raspberry\test.php(13):InitPHP\Coll\Request::get('https://jsonpla...')#1 C:\xamp\htdocs\Raspberry\test.php(25):testRequest()#2{main}在第18行的C:\xampp\htdocs\Raspberry \requests.php中抛出。

    这是requests.php文件;

    <?php
    
    declare(strict_types=1);
    
    namespace InitPHP\Curl;
    
    require_once __DIR__ . '/vendor/autoload.php';
    
    
    use InitPHP\Curl\Curl;  
    use Exception;
    
    class Request
    {
        static function get(string $url, array $query = [], array $headers = [], array $options = [])
        {
            // Create a new instance of the Curl class
            $curl = new Curl();
    
            // Set the URL
            $curl->setUrl($url);
    
            // Construct the full URL with query parameters
            if (!empty($query)) {
                $url .= '?' . http_build_query($query);
            }
    
            // Set custom headers if provided
            if (!empty($headers)) {
                $curl->setHeaders($headers);
            }
    
            // Execute the HTTP request using the Curl class
            if ($curl->handler()) {
                // Get the JSON response
                $response = $curl->getResponse('body');
    
                // Parse JSON response using json_decode
                $jsonData = json_decode($response, true);
    
                if ($jsonData === null) {
                    throw new Exception('Failed to decode JSON response.');
                }
    
                return $jsonData;
            } else {
                throw new Exception($curl->getError());
            }
        }
    }
    
    1. test.php文件;
    <?php 
    use InitPHP\Curl\Request;
    
    require_once 'requests.php'; // Include the request.php file with your Request class
    
    require_once 'vendor/autoload.php';
    
    
    function testRequest()
    {
        try {
            $url = 'https://jsonplaceholder.typicode.com/posts/1';
            $response = Request::get($url);
        
            // Print the JSON response
            echo "JSON Response:\n";
            print_r($response);
        } catch (Exception $e) {
            echo "Error: " . $e->getMessage();
        }
        
    }
    
    // Call your test functions
    testRequest();
    
    1 回复  |  直到 2 年前
        1
  •  0
  •   Bassel Hossam    2 年前

    根据错误消息,似乎没有调用任何类 Curl 所以要确保 Curl.php 文件位于与这两个类相同的目录中,因为导入来自相同的命名空间 use InitPHP\Curl\Curl; 或修复import语句以指向正确的命名空间

    推荐文章