Returning JSON from a PHP Script

前端 未结 18 1401
南方客
南方客 2020-11-21 04:59

I want to return JSON from a PHP script.

Do I just echo the result? Do I have to set the Content-Type header?

相关标签:
18条回答
  • 2020-11-21 05:40

    Whenever you are trying to return JSON response for API or else make sure you have proper headers and also make sure you return a valid JSON data.

    Here is the sample script which helps you to return JSON response from PHP array or from JSON file.

    PHP Script (Code):

    <?php
    
    // Set required headers
    header('Content-Type: application/json; charset=utf-8');
    header('Access-Control-Allow-Origin: *');
    
    /**
     * Example: First
     *
     * Get JSON data from JSON file and retun as JSON response
     */
    
    // Get JSON data from JSON file
    $json = file_get_contents('response.json');
    
    // Output, response
    echo $json;
    
    /** =. =.=. =.=. =.=. =.=. =.=. =.=. =.=. =.=. =.=. =.  */
    
    /**
     * Example: Second
     *
     * Build JSON data from PHP array and retun as JSON response
     */
    
    // Or build JSON data from array (PHP)
    $json_var = [
      'hashtag' => 'HealthMatters',
      'id' => '072b3d65-9168-49fd-a1c1-a4700fc017e0',
      'sentiment' => [
        'negative' => 44,
        'positive' => 56,
      ],
      'total' => '3400',
      'users' => [
        [
          'profile_image_url' => 'http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg',
          'screen_name' => 'rayalrumbel',
          'text' => 'Tweet (A), #HealthMatters because life is cool :) We love this life and want to spend more.',
          'timestamp' => '{{$timestamp}}',
        ],
        [
          'profile_image_url' => 'http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg',
          'screen_name' => 'mikedingdong',
          'text' => 'Tweet (B), #HealthMatters because life is cool :) We love this life and want to spend more.',
          'timestamp' => '{{$timestamp}}',
        ],
        [
          'profile_image_url' => 'http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg',
          'screen_name' => 'ScottMili',
          'text' => 'Tweet (C), #HealthMatters because life is cool :) We love this life and want to spend more.',
          'timestamp' => '{{$timestamp}}',
        ],
        [
          'profile_image_url' => 'http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg',
          'screen_name' => 'yogibawa',
          'text' => 'Tweet (D), #HealthMatters because life is cool :) We love this life and want to spend more.',
          'timestamp' => '{{$timestamp}}',
        ],
      ],
    ];
    
    // Output, response
    echo json_encode($json_var);
    

    JSON File (JSON DATA):

    {
        "hashtag": "HealthMatters", 
        "id": "072b3d65-9168-49fd-a1c1-a4700fc017e0", 
        "sentiment": {
            "negative": 44, 
            "positive": 56
        }, 
        "total": "3400", 
        "users": [
            {
                "profile_image_url": "http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg", 
                "screen_name": "rayalrumbel", 
                "text": "Tweet (A), #HealthMatters because life is cool :) We love this life and want to spend more.", 
                "timestamp": "{{$timestamp}}"
            }, 
            {
                "profile_image_url": "http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg", 
                "screen_name": "mikedingdong", 
                "text": "Tweet (B), #HealthMatters because life is cool :) We love this life and want to spend more.", 
                "timestamp": "{{$timestamp}}"
            }, 
            {
                "profile_image_url": "http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg", 
                "screen_name": "ScottMili", 
                "text": "Tweet (C), #HealthMatters because life is cool :) We love this life and want to spend more.", 
                "timestamp": "{{$timestamp}}"
            }, 
            {
                "profile_image_url": "http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg", 
                "screen_name": "yogibawa", 
                "text": "Tweet (D), #HealthMatters because life is cool :) We love this life and want to spend more.", 
                "timestamp": "{{$timestamp}}"
            }
        ]
    }
    
    

    JSON Screeshot:

    0 讨论(0)
  • 2020-11-21 05:41

    Set the content type with header('Content-type: application/json'); and then echo your data.

    0 讨论(0)
  • 2020-11-21 05:46

    It is also good to set the access security - just replace * with the domain you want to be able to reach it.

    <?php
    header('Access-Control-Allow-Origin: *');
    header('Content-type: application/json');
        $response = array();
        $response[0] = array(
            'id' => '1',
            'value1'=> 'value1',
            'value2'=> 'value2'
        );
    
    echo json_encode($response); 
    ?>
    

    Here is more samples on that: how to bypass Access-Control-Allow-Origin?

    0 讨论(0)
  • 2020-11-21 05:46

    You can use this little PHP library. It sends the headers and give you an object to use it easily.

    It looks like :

    <?php
    // Include the json class
    include('includes/json.php');
    
    // Then create the PHP-Json Object to suits your needs
    
    // Set a variable ; var name = {}
    $Json = new json('var', 'name'); 
    // Fire a callback ; callback({});
    $Json = new json('callback', 'name'); 
    // Just send a raw JSON ; {}
    $Json = new json();
    
    // Build data
    $object = new stdClass();
    $object->test = 'OK';
    $arraytest = array('1','2','3');
    $jsonOnly = '{"Hello" : "darling"}';
    
    // Add some content
    $Json->add('width', '565px');
    $Json->add('You are logged IN');
    $Json->add('An_Object', $object);
    $Json->add("An_Array",$arraytest);
    $Json->add("A_Json",$jsonOnly);
    
    // Finally, send the JSON.
    
    $Json->send();
    ?>
    
    0 讨论(0)
  • 2020-11-21 05:47

    According to the manual on json_encode the method can return a non-string (false):

    Returns a JSON encoded string on success or FALSE on failure.

    When this happens echo json_encode($data) will output the empty string, which is invalid JSON.

    json_encode will for instance fail (and return false) if its argument contains a non UTF-8 string.

    This error condition should be captured in PHP, for example like this:

    <?php
    header("Content-Type: application/json");
    
    // Collect what you need in the $data variable.
    
    $json = json_encode($data);
    if ($json === false) {
        // Avoid echo of empty string (which is invalid JSON), and
        // JSONify the error message instead:
        $json = json_encode(["jsonError" => json_last_error_msg()]);
        if ($json === false) {
            // This should not happen, but we go all the way now:
            $json = '{"jsonError":"unknown"}';
        }
        // Set HTTP response status code to: 500 - Internal Server Error
        http_response_code(500);
    }
    echo $json;
    ?>
    

    Then the receiving end should of course be aware that the presence of the jsonError property indicates an error condition, which it should treat accordingly.

    In production mode it might be better to send only a generic error status to the client and log the more specific error messages for later investigation.

    Read more about dealing with JSON errors in PHP's Documentation.

    0 讨论(0)
  • 2020-11-21 05:51

    Try json_encode to encode the data and set the content-type with header('Content-type: application/json');.

    0 讨论(0)
提交回复
热议问题