简体   繁体   中英

json_encode() expects parameter 2 to be long, string given

I'm trying to return a JSON from a REST Service using this code:

$categories = $categoriesController->listAll();
if($categories){
   header($_SERVER["SERVER_PROTOCOL"] . " 200 OK");
   header("Content-Type: application/json");
   echo json_encode($categories,JSON_PRETTY_PRINT);
}else{

}

But I get this error:

json_encode() expects parameter 2 to be long, string given

I've seen several examples use the exact same code so I don't understand why i'm getting this issue. I'd appreciate some help with this problem. Thanks :)

The constant JSON_PRETTY_PRINT is only available for PHP versions >= 5.4. It's value is 128, so try replacing JSON_PRETTY_PRINT with 128

echo json_encode($categories,128);

JSON_PRETTY_PRINT was introduced in PHP 5.4.0 .

If you would like to make your code more readable in earlier versions of PHP, use these constants instead of their numerical values. Notice that I put the version each became available--if you use an option in an earlier version of PHP, don't expect it to work.

<?php
   // json_encode() options
   define('JSON_HEX_TAG',                1);    // Since PHP 5.3.0
   define('JSON_HEX_AMP',                2);    // Since PHP 5.3.0
   define('JSON_HEX_APOS',               4);    // Since PHP 5.3.0
   define('JSON_HEX_QUOT',               8);    // Since PHP 5.3.0
   define('JSON_FORCE_OBJECT',           16);   // Since PHP 5.3.0
   define('JSON_NUMERIC_CHECK',          32);   // Since PHP 5.3.3
   define('JSON_UNESCAPED_SLASHES',      64);   // Since PHP 5.4.0
   define('JSON_PRETTY_PRINT',           128);  // Since PHP 5.4.0
   define('JSON_UNESCAPED_UNICODE',      256);  // Since PHP 5.4.0

   // json_decode() options
   define('JSON_OBJECT_AS_ARRAY',        1);    // Since PHP 5.4.0
   define('JSON_BIGINT_AS_STRING',       2);    // Since PHP 5.4.0
   define('JSON_PARSE_JAVASCRIPT',       4);    // upgrade.php

   // json_last_error() error codes
   define('JSON_ERROR_NONE',             0);    // Since PHP 5.3.0
   define('JSON_ERROR_DEPTH',            1);    // Since PHP 5.3.0
   define('JSON_ERROR_STATE_MISMATCH',   2);    // Since PHP 5.3.0
   define('JSON_ERROR_CTRL_CHAR',        3);    // Since PHP 5.3.0
   define('JSON_ERROR_SYNTAX',           4);    // Since PHP 5.3.0
   define('JSON_ERROR_UTF8',             5);    // Since PHP 5.3.3
   define('JSON_ERROR_RECURSION',        6);    // Since PHP 5.5.0
   define('JSON_ERROR_INF_OR_NAN',       7);    // Since PHP 5.5.0
   define('JSON_ERROR_UNSUPPORTED_TYPE', 8);    // Since PHP 5.5.0
?>

JSON_PRETTY_PRINT选项仅在PHP 5.4中可用

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM