从PHP脚本返回JSON

我想从PHP脚本返回JSON

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


#1楼

返回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楼

您可以使用这个小的PHP库 。 它发送标题,并给您一个易于使用的对象。

看起来像 :

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

#3楼

如果您需要从php发送自定义信息获取json,则可以添加此header('Content-Type: application/json'); 在打印任何其他东西之前,因此可以打印自定义echo '{"monto": "'.$monto[0]->valor.'","moneda":"'.$moneda[0]->nombre.'","simbolo":"'.$moneda[0]->simbolo.'"}';


#4楼

根据json_encode上的手册,该方法可以返回非字符串( false ):

如果成功,则返回JSON编码的字符串; FALSE失败,则返回FALSE

发生这种情况时, echo json_encode($data)将输出空字符串,该字符串是无效的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的文档中阅读有关处理JSON错误的更多信息


#5楼

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


#6楼

您问题的答案在这里

它说。

JSON文本的MIME媒体类型为application / json。

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


#7楼

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


#8楼

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


#9楼

通常,没有它会没事,但是您可以并且应该设置Content-Type标头:

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

如果不使用特定的框架,通常会允许一些请求参数来修改输出行为。 通常,为了快速进行故障排除,不发送标头,或者有时将数据有效载荷print_r盯着它很有用(尽管在大多数情况下,它不是必需的)。


#10楼

如上所述:

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

将工作。 但请记住:

  • 即使不使用此标头,Ajax都可以读取json,除非您的json包含一些HTML标记。 在这种情况下,您需要将标头设置为application / json。

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


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

这里有更多示例: 如何绕过Access-Control-Allow-Origin?


#12楼

这是一个简单的PHP脚本,用于返回雄性雌性,并且用户ID作为json值将是您调用脚本json.php时的任何随机值。

希望这个帮助谢谢

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

#13楼

如果查询数据库并需要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解析结果,请看一下本教程


#14楼

将域对象格式化为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楼

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

#16楼

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

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

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

    header('Status: ' . $httpStatus);

    echo json_encode($data);

    exit();
}

#17楼

每当您尝试返回API的JSON响应时,否则请确保您具有正确的标头,并且还应确保返回有效的JSON数据。

这是示例脚本,可帮助您从PHP数组或JSON文件返回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:

在此处输入图片说明

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值