从PHP脚本返回JSON

时间:2010-10-31 18:23:55

标签: php json header

我想从PHP脚本返回JSON。

我只是回应结果吗?我是否必须设置Content-Type标题?

19 个答案:

答案 0 :(得分:1369)

虽然没有它你通常很好,你可以并且应该设置Content-Type标题:

<?PHP
$data = /** whatever you're serializing **/;
header('Content-Type: application/json');
echo json_encode($data);

如果我没有使用特定的框架,我通常会允许一些请求参数来修改输出行为。它通常用于快速故障排除,不发送标题,或者有时print_r数据有效负载以引人注目(尽管在大多数情况下,它不是必需的)。

答案 1 :(得分:106)

返回JSON的一整套漂亮而清晰的PHP代码是:

$option = $_GET['option'];

if ( $option == 1 ) {
    $data = [ 'a', 'b', 'c' ];
    // will encode to JSON array: ["a","b","c"]
    // accessed as example in JavaScript like: result[1] (returns "b")
} else {
    $data = [ 'name' => 'God', 'age' => -1 ];
    // will encode to JSON object: {"name":"God","age":-1}  
    // accessed as example in JavaScript like: result.name or result['name'] (returns "God")
}

header('Content-type: application/json');
echo json_encode( $data );

答案 2 :(得分:37)

尝试json_encode对数据进行编码,并使用header('Content-type: application/json');设置内容类型。

答案 3 :(得分:36)

根据manual on json_encode,该方法可以返回非字符串( false ):

  

成功时返回JSON编码的字符串或失败时返回FALSE

当发生这种情况时echo json_encode($data)将输出空字符串,即invalid JSON

如果

json_encode的参数包含非UTF-8字符串,则会失败(并返回false)。

应该在PHP中捕获此错误情况,例如:

<?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(array("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;
?>

然后接收端当然应该知道 jsonError 属性的存在表明错误情况,它应该相应地处理。

在生产模式下,最好只向客户端发送一般错误状态,并记录更具体的错误消息以供日后调查。

阅读PHP's Documentation中有关处理JSON错误的更多信息。

答案 4 :(得分:15)

使用header('Content-type: application/json');设置内容类型,然后回显您的数据。

答案 5 :(得分:11)

设置访问安全性也很好 - 只需将*替换为您希望能够访问它的域。

<?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); 
?>

以下是更多示例:how to bypass Access-Control-Allow-Origin?

答案 6 :(得分:6)

这个问题有很多答案,但是没有一个问题涵盖了返回干净的JSON的整个过程,以及防止JSON响应格式错误的一切。


/*
 * returnJsonHttpResponse
 * @param $success: Boolean
 * @param $data: Object or Array
 */
function returnJsonHttpResponse($success, $data)
{
    // remove any string that could create an invalid JSON 
    // such as PHP Notice, Warning, logs...
    ob_clean();

    // this will clean up any previously added headers, to start clean
    header_remove(); 

    // Set the content type to JSON and charset 
    // (charset can be set to something else)
    header("Content-type: application/json; charset=utf-8");

    // Set your HTTP response code, 2xx = SUCCESS, 
    // anything else will be error, refer to HTTP documentation
    if ($success) {
        http_response_code(200);
    } else {
        http_response_code(500);
    }
    
    // encode your PHP Object or Array into a JSON string.
    // stdClass or array
    echo json_encode($data);

    // making sure nothing is added
    exit();
}

参考:

response_remove

ob_clean

Content-type JSON

HTTP Codes

http_response_code

json_encode

答案 7 :(得分:3)

您的问题的答案is here

它说。

  

JSON文本的MIME媒体类型是   应用/ JSON。

因此,如果您将标头设置为该类型,并输出您的JSON字符串,它应该可以正常工作。

答案 8 :(得分:3)

<?php
$data = /** whatever you're serializing **/;
header("Content-type: application/json; charset=utf-8");
echo json_encode($data);
?>

答案 9 :(得分:3)

如上所述:

header('Content-Type: application/json');

将完成这项工作。但请记住:

  • 即使你的json包含一些HTML标签,Ajax也没有问题来读取json,即使没有使用这个标头。在这种情况下,您需要将标题设置为application / json。

  • 确保您的文件未以UTF8-BOM编码。此格式在文件顶部添加一个字符,因此header()调用将失败。

答案 10 :(得分:1)

如果您需要从php发送自定义信息的json,您可以在打印任何其他内容之前添加此#include "provedorimagem.h" #include <QDebug> provedorImagem::provedorImagem() : QQuickImageProvider(QQuickImageProvider::Image) { } QImage provedorImagem::requestImage(const QString &id, QSize *size, const QSize &requestedSize) { if(imagem.isNull()) { qDebug() << "Erro ao prover a imagem"; } return imagem; } void provedorImagem::carregaImagem(QImage imagemRecebida) { imagem = imagemRecebida; } ,那么您可以打印自己的 import math ... for i in range(bound): temp=i emptyFound = False for j in range(2): result=search_combination(data,target+(math.pow(-1, j) * temp)) if result !=[]: emptyFound = True break if emptyFound == True: break; return [result,temp]

答案 11 :(得分:1)

这是一个简单的PHP脚本,用于返回男性女性和用户ID,因为当您调用脚本json.php时,json值将是任意随机值。

希望此帮助谢谢

<?php
header("Content-type: application/json");
$myObj=new \stdClass();
$myObj->user_id = rand(0, 10);
$myObj->male = rand(0, 5);
$myObj->female = rand(0, 5);
$myJSON = json_encode($myObj);
echo $myJSON;
?>

答案 12 :(得分:1)

是的,您需要使用echo来显示输出。 Mimetype:application / json

答案 13 :(得分:0)

如果查询数据库并需要JSON格式的结果集,可以这样做:

<?php

$db = mysqli_connect("localhost","root","","mylogs");
//MSG
$query = "SELECT * FROM logs LIMIT 20";
$result = mysqli_query($db, $query);
//Add all records to an array
$rows = array();
while($row = $result->fetch_array()){
    $rows[] = $row;
}
//Return result to jTable
$qryResult = array();
$qryResult['logs'] = $rows;
echo json_encode($qryResult);

mysqli_close($db);

?>

有关使用jQuery解析结果的帮助,请查看this tutorial

答案 14 :(得分:0)

将域对象格式化为JSON的简便方法是使用Marshal Serializer。 然后将数据传递给json_encode并根据您的需要发送正确的Content-Type标头。 如果您使用的是像Symfony这样的框架,则不需要手动设置标头。在那里,您可以使用JsonResponse

例如,处理Javascript的正确Content-Type为application/javascript

或者,如果您需要支持一些非常古老的浏览器,最安全的是text/javascript

对于移动应用等所有其他用途,请使用application/json作为内容类型。

这是一个小例子:

<?php
...
$userCollection = [$user1, $user2, $user3];

$data = Marshal::serializeCollectionCallable(function (User $user) {
    return [
        'username' => $user->getUsername(),
        'email'    => $user->getEmail(),
        'birthday' => $user->getBirthday()->format('Y-m-d'),
        'followers => count($user->getFollowers()),
    ];
}, $userCollection);

header('Content-Type: application/json');
echo json_encode($data);

答案 15 :(得分:0)

您可以使用此little PHP library。它会发送标题并为您提供一个易于使用的对象。

看起来像:

<?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();
?>

答案 16 :(得分:0)

一个简单的函数,用于返回带有 HTTP状态代码 JSON响应

function json_response($data=null, $httpStatus=200)
{
    header_remove();

    header("Content-Type: application/json");

    header('Status: ' . $httpStatus);

    http_response_code($httpStatus);

    echo json_encode($data);
}

答案 17 :(得分:0)

无论何时尝试返回API的JSON响应,或者确保您具有正确的标头,并确保您返回有效的JSON数据。

这是示例脚本,可帮助您从PHP数组或 来自JSON文件。

  

PHP脚本(代码):

<?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文件(JSON数据):

{
    "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:

enter image description here

答案 18 :(得分:0)

如果您在 WordPress 中执行此操作,则有一个简单的解决方案:

add_action( 'parse_request', function ($wp) {
    $data = /* Your data to serialise. */
    wp_send_json_success($data); /* Returns the data with a success flag. */
    exit(); /* Prevents more response from the server. */
})

请注意,这不在 wp_head 钩子中,即使您立即退出,它也会始终返回大部分头部。 parse_request 在序列中出现得更早。