Hướng dẫn http request php json - http yêu cầu php json

Vấn đề của bạn có là chuỗi này không phải là json thích hợp: [500,'hello world']

Đây sẽ là JSON [500,"hello world"] thích hợp. JSON rất nghiêm ngặt về định dạng và yêu cầu tất cả các giá trị chuỗi phải được bọc trong các trích dẫn kép và không bao giờ trích dẫn đơn.

Điều thích hợp cần làm để tránh các vấn đề, sẽ là sử dụng các hàm PHP json_encode()json_decode()

Ví dụ,


Và trong bài đăng.php bạn sẽ đọc nó như vậy,


Cờ true trong json_decode() cho biết chức năng mà bạn muốn nó là một mảng kết hợp chứ không phải là một đối tượng PHP, đó là hành vi mặc định của nó.

Hàm


1 sẽ xuất cấu trúc PHP của mảng JSON được chuyển đổi:

Array(
    [0] => 500
    [1] => hello world
) 

Trong hướng dẫn này, chúng tôi sẽ chỉ cho bạn cách gửi dữ liệu JSON trong PHP.

Trong một số trường hợp nhất định, bạn sẽ bắt gặp các dịch vụ web và API sẽ yêu cầu bạn gửi JSON qua yêu cầu POST.

Cách dễ nhất để đạt được điều này là bằng cách sử dụng các chức năng Curl PHP.

Hãy xem ví dụ sau.

//The URL of the API.
$url = 'http://example.com/api/JSON/create';

//Initiate cURL.
$ch = curl_init($url);

//The JSON data.
$jsonData = array(
    'username' => 'MyUsername',
    'password' => 'MyPassword'
);

//Encode the array into JSON.
$jsonDataEncoded = json_encode($jsonData);

//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);

//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);

//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 

//Execute the request
$result = curl_exec($ch);

Trong mã trên, chúng tôi đã làm như sau.

  1. Chúng tôi đã chỉ định URL mà chúng tôi muốn gửi JSON của chúng tôi đến. Đây thường là URL của API mà chúng tôi muốn gửi dữ liệu đến.
  2. Sau đó, chúng tôi đã bắt đầu Curl bằng cách sử dụng chức năng Curl_init.curl_init function.
  3. Sau đó, chúng tôi thiết lập một mảng PHP chứa dữ liệu mẫu.
  4. Chúng tôi đã mã hóa mảng PHP & nbsp; mảng thành chuỗi JSON bằng cách sử dụng hàm json_encode.
  5. Chúng tôi khi nói Curl rằng chúng tôi muốn gửi yêu cầu bài viết bằng cách đặt tùy chọn Curlopt_Post thành 1.CURLOPT_POST option to 1.
  6. Sau đó, chúng tôi đã đính kèm dữ liệu JSON của mình bằng cách sử dụng tùy chọn Curlopt_PostFields.CURLOPT_POSTFIELDS option.
  7. Sau đó, chúng tôi đặt loại nội dung của yêu cầu của chúng tôi thành ứng dụng/json & nbsp; bằng cách sử dụng tùy chọn Curlopt_httpheader. Điều cực kỳ quan trọng cần lưu ý là bạn nên luôn luôn sử dụng ứng dụng/json, chứ không phải văn bản/json. Nói một cách đơn giản, sử dụng văn bản/json, không chính xác và có thể dẫn đến lỗi!application/json using the CURLOPT_HTTPHEADER option. It is extremely important to note that you should always use “application/json”, not “text/json”. Simply put, using “text/json” is incorrect and may lead to errors!
  8. Cuối cùng, chúng tôi sử dụng chức năng Curl_Exec để thực hiện yêu cầu bài đăng của chúng tôi. Nếu bạn muốn kiểm tra các lỗi ở giai đoạn này, thì bạn nên kiểm tra bài viết của chúng tôi về xử lý lỗi với Curl.curl_exec to execute our POST request. If you want to check for errors at this stage, then you should check out our article on error handling with cURL.

Như bạn có thể thấy, nó không khác nhiều so với việc gửi một yêu cầu bài thường xuyên. Trên thực tế, sự khác biệt thực sự duy nhất là chúng tôi đặt loại nội dung thành Ứng dụng/JSON.application/json.

Liên quan: Cách truy xuất dữ liệu bài JSON RAW với PHP.

Xem thảo luận

Cải thiện bài viết

Lưu bài viết

  • Đọc
  • Bàn luận
  • Xem thảo luận

    Cải thiện bài viết

    Lưu bài viết

    Đọc

    • Bàn luận: This is a read-only stream that allows us to read raw data from the request body. It returns all the raw data after the HTTP headers of the request, regardless of the content type.
    • Trong bài viết này, chúng ta sẽ xem cách truy xuất bài đăng JSON với PHP, và cũng sẽ thấy việc triển khai của họ thông qua các ví dụ. Đầu tiên, chúng tôi sẽ tìm kiếm các tính năng dưới đây 3: function: This function in PHP is used to read a file into a string.
    • PHP: // Đầu vào: Đây là luồng chỉ đọc cho phép chúng tôi đọc dữ liệu thô từ thân yêu cầu. Nó trả về tất cả các dữ liệu thô sau các tiêu đề HTTP của yêu cầu, bất kể loại nội dung. function: This function takes a JSON string and converts it into a PHP variable that may be an array or an object.

    file_get_contents () Hàm: Hàm này trong PHP được sử dụng để đọc một tệp vào một chuỗi.$_POST[] global variable. But this fails in the case when we want to receive JSON string as post data. To receive JSON string we can use the “php://input” along with the function file_get_contents() which helps us receive JSON data as a file and read it into a string. Later, we can use the json_decode() function to decode the JSON string.

    Chức năng JSON_DECODE (): Hàm này lấy chuỗi JSON và chuyển đổi nó thành biến PHP có thể là một mảng hoặc một đối tượng.:

    // Takes raw data from the request
    $json = file_get_contents('php://input');
    
    // Converts it into a PHP object
    $data = json_decode($json);

    Được biết, tất cả dữ liệu bài đăng có thể được nhận trong tập lệnh PHP bằng cách sử dụng biến toàn cầu $ _POST []. Nhưng điều này thất bại trong trường hợp khi chúng tôi muốn nhận Chuỗi JSON dưới dạng dữ liệu POST. Để nhận chuỗi JSON, chúng tôi có thể sử dụng php: // nhập vào cùng với hàm file_get_contents () giúp chúng tôi nhận dữ liệu JSON dưới dạng tệp và đọc nó thành chuỗi. & NBSP; Sau này, chúng tôi có thể sử dụng hàm json_decode () Để giải mã chuỗi JSON. This example uses the json_decode() function that is used to decode a JSON string.

    Xử lý các yêu cầu bài đăng JSON:

    
    
    2

    Ví dụ 1: & nbsp; Ví dụ này sử dụng hàm json_decode () được sử dụng để giải mã chuỗi JSON.

    PHP

    
    
    3
    
    
    4
    
    
    5
    
    
    6
    
    
    7

    Array(
        [0] => 500
        [1] => hello world
    ) 
    
    7

    
    
    3
    
    
    9
    Array(
        [0] => 500
        [1] => hello world
    ) 
    
    0
    
    
    4
    Array(
        [0] => 500
        [1] => hello world
    ) 
    
    2
    This example uses the json_decode() function that is used to decode a JSON string.

    Xử lý các yêu cầu bài đăng JSON:

    
    
    2

    Ví dụ 1: & nbsp; Ví dụ này sử dụng hàm json_decode () được sử dụng để giải mã chuỗi JSON.

    PHP

    //The URL of the API.
    $url = 'http://example.com/api/JSON/create';
    
    //Initiate cURL.
    $ch = curl_init($url);
    
    //The JSON data.
    $jsonData = array(
        'username' => 'MyUsername',
        'password' => 'MyPassword'
    );
    
    //Encode the array into JSON.
    $jsonDataEncoded = json_encode($jsonData);
    
    //Tell cURL that we want to send a POST request.
    curl_setopt($ch, CURLOPT_POST, 1);
    
    //Attach our encoded JSON string to the POST fields.
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
    
    //Set the content type to application/json
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 
    
    //Execute the request
    $result = curl_exec($ch);
    2
    //The URL of the API.
    $url = 'http://example.com/api/JSON/create';
    
    //Initiate cURL.
    $ch = curl_init($url);
    
    //The JSON data.
    $jsonData = array(
        'username' => 'MyUsername',
        'password' => 'MyPassword'
    );
    
    //Encode the array into JSON.
    $jsonDataEncoded = json_encode($jsonData);
    
    //Tell cURL that we want to send a POST request.
    curl_setopt($ch, CURLOPT_POST, 1);
    
    //Attach our encoded JSON string to the POST fields.
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
    
    //Set the content type to application/json
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 
    
    //Execute the request
    $result = curl_exec($ch);
    8
    //The URL of the API.
    $url = 'http://example.com/api/JSON/create';
    
    //Initiate cURL.
    $ch = curl_init($url);
    
    //The JSON data.
    $jsonData = array(
        'username' => 'MyUsername',
        'password' => 'MyPassword'
    );
    
    //Encode the array into JSON.
    $jsonDataEncoded = json_encode($jsonData);
    
    //Tell cURL that we want to send a POST request.
    curl_setopt($ch, CURLOPT_POST, 1);
    
    //Attach our encoded JSON string to the POST fields.
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
    
    //Set the content type to application/json
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 
    
    //Execute the request
    $result = curl_exec($ch);
    4
    // Takes raw data from the request
    $json = file_get_contents('php://input');
    
    // Converts it into a PHP object
    $data = json_decode($json);
    0

    
    
    3
    // Takes raw data from the request
    $json = file_get_contents('php://input');
    
    // Converts it into a PHP object
    $data = json_decode($json);
    2

    PHP

    
    
    3
    
    
    4
    
    
    5
    
    
    6
    
    
    7

    
    
    3
    
    
    9
    Array(
        [0] => 500
        [1] => hello world
    ) 
    
    0
    
    
    4
    Array(
        [0] => 500
        [1] => hello world
    ) 
    
    2

    
    
    3
    Array(
        [0] => 500
        [1] => hello world
    ) 
    
    4
    
    
    9
    Array(
        [0] => 500
        [1] => hello world
    ) 
    
    6

    Array(
        [0] => 500
        [1] => hello world
    ) 
    
    7

    Ví dụ 2: Ví dụ này sử dụng hàm json_decode () được sử dụng để giải mã chuỗi JSON.


    3 4 //The URL of the API. $url = 'http://example.com/api/JSON/create'; //Initiate cURL. $ch = curl_init($url); //The JSON data. $jsonData = array( 'username' => 'MyUsername', 'password' => 'MyPassword' ); //Encode the array into JSON. $jsonDataEncoded = json_encode($jsonData); //Tell cURL that we want to send a POST request. curl_setopt($ch, CURLOPT_POST, 1); //Attach our encoded JSON string to the POST fields. curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded); //Set the content type to application/json curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); //Execute the request $result = curl_exec($ch);1

    //The URL of the API.
    $url = 'http://example.com/api/JSON/create';
    
    //Initiate cURL.
    $ch = curl_init($url);
    
    //The JSON data.
    $jsonData = array(
        'username' => 'MyUsername',
        'password' => 'MyPassword'
    );
    
    //Encode the array into JSON.
    $jsonDataEncoded = json_encode($jsonData);
    
    //Tell cURL that we want to send a POST request.
    curl_setopt($ch, CURLOPT_POST, 1);
    
    //Attach our encoded JSON string to the POST fields.
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
    
    //Set the content type to application/json
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 
    
    //Execute the request
    $result = curl_exec($ch);
    2
    //The URL of the API.
    $url = 'http://example.com/api/JSON/create';
    
    //Initiate cURL.
    $ch = curl_init($url);
    
    //The JSON data.
    $jsonData = array(
        'username' => 'MyUsername',
        'password' => 'MyPassword'
    );
    
    //Encode the array into JSON.
    $jsonDataEncoded = json_encode($jsonData);
    
    //Tell cURL that we want to send a POST request.
    curl_setopt($ch, CURLOPT_POST, 1);
    
    //Attach our encoded JSON string to the POST fields.
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
    
    //Set the content type to application/json
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 
    
    //Execute the request
    $result = curl_exec($ch);
    3
    //The URL of the API.
    $url = 'http://example.com/api/JSON/create';
    
    //Initiate cURL.
    $ch = curl_init($url);
    
    //The JSON data.
    $jsonData = array(
        'username' => 'MyUsername',
        'password' => 'MyPassword'
    );
    
    //Encode the array into JSON.
    $jsonDataEncoded = json_encode($jsonData);
    
    //Tell cURL that we want to send a POST request.
    curl_setopt($ch, CURLOPT_POST, 1);
    
    //Attach our encoded JSON string to the POST fields.
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
    
    //Set the content type to application/json
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 
    
    //Execute the request
    $result = curl_exec($ch);
    4
    //The URL of the API.
    $url = 'http://example.com/api/JSON/create';
    
    //Initiate cURL.
    $ch = curl_init($url);
    
    //The JSON data.
    $jsonData = array(
        'username' => 'MyUsername',
        'password' => 'MyPassword'
    );
    
    //Encode the array into JSON.
    $jsonDataEncoded = json_encode($jsonData);
    
    //Tell cURL that we want to send a POST request.
    curl_setopt($ch, CURLOPT_POST, 1);
    
    //Attach our encoded JSON string to the POST fields.
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
    
    //Set the content type to application/json
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 
    
    //Execute the request
    $result = curl_exec($ch);
    5
    //The URL of the API.
    $url = 'http://example.com/api/JSON/create';
    
    //Initiate cURL.
    $ch = curl_init($url);
    
    //The JSON data.
    $jsonData = array(
        'username' => 'MyUsername',
        'password' => 'MyPassword'
    );
    
    //Encode the array into JSON.
    $jsonDataEncoded = json_encode($jsonData);
    
    //Tell cURL that we want to send a POST request.
    curl_setopt($ch, CURLOPT_POST, 1);
    
    //Attach our encoded JSON string to the POST fields.
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
    
    //Set the content type to application/json
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 
    
    //Execute the request
    $result = curl_exec($ch);
    6change the method next to the URL to 'POST', and under the 'Body' tab choose the 'raw' radio button and then 'JSON (application/json)' from the drop down. You can now type in the JSON you want to send along with the POST request. If this is successful, you should see the new data in your 'db.

    3Array( [0] => 500 [1] => hello world ) 4 9[500,'hello world']1

    Tệp PHP được giải thích: Chuyển đổi yêu cầu thành một đối tượng, sử dụng hàm PHP json_decode ().Truy cập cơ sở dữ liệu và điền vào một mảng với dữ liệu được yêu cầu.Thêm mảng vào một đối tượng và trả về đối tượng dưới dạng JSON bằng hàm json_encode ().Convert the request into an object, using the PHP function json_decode(). Access the database, and fill an array with the requested data. Add the array to an object, and return the object as JSON using the json_encode() function.

    Làm thế nào để nhận phản hồi JSON từ API REST trong PHP?

    Để nhận JSON từ điểm cuối API REST, bạn phải gửi yêu cầu HTTP nhận đến Máy chủ API REST và cung cấp tiêu đề yêu cầu ứng dụng/Ứng dụng/JSON.Tiêu đề chấp nhận cho máy chủ API REST rằng máy khách API mong đợi JSON.send an HTTP GET request to the REST API server and provide an Accept: application/json request header. The Accept header tells the REST API server that the API client expects JSON.

    Giá trị JSON được truy cập như thế nào trong PHP?

    PHP và JSON..

    Hàm json_encode () được sử dụng để mã hóa định dạng JSON cho định dạng JSON ..

    Hàm json_decode () được sử dụng để giải mã đối tượng JSON thành đối tượng PHP hoặc mảng kết hợp ..

    Hàm json_decode () trả về một đối tượng theo mặc định.....

    Bạn cũng có thể lặp qua các giá trị với vòng lặp foreach ():.