PHP ස්ක්‍රිප්ට් එකකින් JSON නැවත ලබා දීම


899

මට JSON PHP පිටපතකින් ආපසු ලබා දීමට අවශ්‍යයි.

මම ප්‍රති result ලය දෝංකාර දෙනවාද? මට Content-Typeශීර්ෂකය සැකසිය යුතුද?

Answers:


1652

ඔබ සාමාන්‍යයෙන් එය නොමැතිව හොඳින් සිටින අතර, ඔබට Content-Typeශීර්ෂකය සැකසිය හැකිය :

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

මම විශේෂිත රාමුවක් භාවිතා නොකරන්නේ නම්, ප්‍රතිදාන හැසිරීම වෙනස් කිරීමට මම සාමාන්‍යයෙන් සමහර ඉල්ලීම් පරාමිතීන්ට ඉඩ දෙමි. සාමාන්‍යයෙන් ඉක්මන් දෝශ නිරාකරණය සඳහා, ශීර්ෂයක් නොයැවීම හෝ සමහර print_rවිට දත්ත ගෙවීම ඇහිබැම වෙත යොමු කිරීම ප්‍රයෝජනවත් විය හැකිය (බොහෝ අවස්ථාවලදී එය අවශ්‍ය නොවිය යුතුය).


9
"දැනටමත් යවා ඇති ශීර්ෂයන්" අනතුරු ඇඟවීම් වලක්වා ගැනීම සඳහා ඔබ ප්‍රතිදාන බෆරයට අමතරව ශීර්ෂ () විධානයන් භාවිතා කළ යුතුය
කෙවින්

6
BOM ගොනුව UTF-8 හි BOM නොමැතිව කේතනය කළ යුතුය :)
Krzysztof Kalinowski

224
header('Content-type:application/json;charset=utf-8');
ටිමෝ හුවොනිනන්

16
ikemikepote PHP ගොනුවේ ඉහළින්ම ශීර්ෂ විධානය තිබිය යුතු යැයි මම නොසිතමි. ඔබ නොදැනුවත්වම දේවල් කෙළ ගසන්නේ නම් සහ එය ඔබේ ශීර්ෂ විධානය වේගවත් කරයි නම්, ඔබේ කේතය කැඩී ඇති හෙයින් එය නිවැරදි කළ යුතුය.
Halfstop

8
RKrzysztofKalinowski නැත, PHP ගොනුව UTF-8 කේතනය කිරීම අවශ්‍ය නොවේ. ප්‍රතිදානය UTF-8 කේතනය කළ යුතුය. එම වැරදි ප්‍රකාශයන් පළපුරුදු නොවන පරිශීලකයින්ට දේවල් බිඳීමෙන් වළක්වා ගන්නේ කෙසේද යන්න ඉගෙන ගැනීමට උපකාරී නොවේ, නමුත් එය ඔවුන් පිළිබඳ මිථ්‍යාවන් වර්ධනය කිරීමට උපකාරී වන අතර ධාරාවන්හි කේතීකරණයේ කාර්යභාරය කුමක්ද සහ ඒවා ක්‍රියා කරන්නේ කෙසේද යන්න ඉගෙන නොගනී.
Áxel කොස්ටාස් පෙනා

126

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

46

ක්‍රමයේ අත්පොතටjson_encode අනුව නූල් නොවන ( අසත්‍ය ) ආපසු ලබා දිය හැකිය :

සාර්ථකත්වය හෝ FALSEඅසාර්ථකත්වය මත JSON කේතනය කළ නූලක් ලබා දෙයි .

මෙය සිදු වූ විට echo json_encode($data)හිස් නූලක් ප්‍රතිදානය කරනු ඇත, එය අවලංගු JSON වේ.

json_encodeඋදාහරණයක් ලෙස falseඑහි තර්කයේ UTF-8 නොවන නූලක් තිබේ නම් එය අසාර්ථක වේ (සහ ආපසු ).

මෙම දෝෂ තත්වය 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(["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 දෝෂ සමඟ කටයුතු කිරීම පිළිබඳ වැඩිදුර කියවන්න .


2
charsetJSON සඳහා පරාමිතියක් නොමැත ; මෙවලම් අවසානයේ සටහන බලන්න. අයිටීඑෆ්.ආර් . (JSON එක් මෙවලමකට යූටීඑෆ් -8 ලෙස සම්ප්‍රේෂණය කළ යුතුය .
පැට්රික් අඳුරු

1
එය ඉස්මතු කිරීමට ස්තූතියි, at පැට්‍රික් ඩාර්ක්. අතිරික්ත charsetපරාමිතිය HTTP ශීර්ෂ නූලෙන් ඉවත් කර ඇත.
ට්‍රින්කෝට්

38

දත්ත සංකේතනය කිරීමට json_encode උත්සාහ කර අන්තර්ගත වර්ගය සකසන්න header('Content-type: application/json');.


15

අන්තර්ගත වර්ගය සමඟ සකසා header('Content-type: application/json');ඔබේ දත්ත ප්‍රතිරාවය කරන්න.


14

ප්‍රවේශවීමේ ආරක්ෂාව සැකසීමද හොඳය - ඔබට එය වෙත ළඟා වීමට අවශ්‍ය වසම වෙනුවට ආදේශ කරන්න.

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

මෙන්න ඒ පිළිබඳ තවත් සාම්පල: ප්‍රවේශ-පාලනය-ඉඩ දෙන්න-සම්භවය මඟ හරින්නේ කෙසේද?


මෙය ක්‍රියාත්මක නොවන්නේ නම් එයින් අදහස් කරන්නේ කුමක්ද? උදාහරණයක් ලෙස, කෝඩ්පෙන් වෙතින් ලැබෙන ඇමතුම් වලට පමණක් සීමා කිරීමට, මම උත්සාහ කළෙමි header('Access-Control-Allow-Origin: https://cdpn.io');, නමුත් මට තවමත් මගේ බ්‍රව්සරයෙන් පිටුව පූරණය කළ හැකිය.
ashleedawg

එය හරස් ස්ක්‍රිප්ටින් අවහිර කිරීම සඳහා භාවිතා කරයි (එක් පිටපතක් තවත් පිටුවක් අමතයි). එබැවින් ඔබට එය ඔබගේ බ්‍රව්සරයෙන් කෙලින්ම පූරණය කිරීමට හැකි වනු ඇත, නමුත් ඔබට එය වෙනත් වසමකින් ස්ක්‍රිප්ට් භාවිතයෙන් පූරණය කළ නොහැක.
ආචාර්ය ආරොන් ඩිෂ්නෝ

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

අක්ෂර මාලාව ශීර්ෂයේ සඳහන් කිරීමේ වෙනස කුමක්ද? කරුණාකර පැහැදිලි කරන්න, ස්තූතියි.
සැන්ක්සොෆොන්

6

ඉහත සඳහන් කළ පරිදි:

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

රැකියාව කරයි. නමුත් එය මතක තබා ගන්න:

  • ඔබේ ශීර්ෂය සමහර HTML ටැග් අඩංගු නම් හැර, මෙම ශීර්ෂකය භාවිතා නොකළද, අජැක්ස් හට json කියවීමට කිසිදු ගැටළුවක් නොමැත. මෙම අවස්ථාවේදී ඔබ ශීර්ෂකය යෙදුම / json ලෙස සැකසිය යුතුය.

  • ඔබගේ ගොනුව UTF8-BOM හි කේතනය කර නොමැති බවට වග බලා ගන්න. මෙම ආකෘතිය ගොනුවේ ඉහළින් අක්ෂරයක් එක් කරයි, එබැවින් ඔබගේ ශීර්ෂ () ඇමතුම අසාර්ථක වනු ඇත.


5

HTTP තත්ව කේතය සමඟ JSON ප්‍රතිචාරයක් ලබා දීම සඳහා සරල කාර්යයකි .

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

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

    http_response_code($httpStatus);

    echo json_encode($data);

    exit();
}

1
header_remove, සහ http ප්‍රතිචාරය පැහැදිලිව සැකසීම හොඳ අදහසකි; තත්වය සැකසීමෙන් පසුව http_response අතිරික්තයක් ලෙස පෙනේ. exitඅවසානයට ප්‍රකාශයක් එක් කිරීමට ද අවශ්‍ය විය හැකිය . මම ඔබේ ක්‍රියාකාරිත්වය rtrincot ගේ: stackoverflow.com/a/35391449/339440
ස්ටීවන් ආර්

යෝජනාවට ස්තූතියි. මම පිළිතුර යාවත්කාලීන කළා.
ඩෑන්

3

ඔබේ ප්‍රශ්නයට පිළිතුර මෙහි ඇත ,

එය පවසයි.

JSON පෙළ සඳහා MIME මාධ්‍ය වර්ගය යෙදුම / json වේ.

එබැවින් ඔබ ශීර්ෂකය එම වර්ගයට සකසා ඔබේ JSON නූල ප්‍රතිදානය කරන්නේ නම් එය ක්‍රියාත්මක විය යුතුය.


2

මෙම ප්‍රශ්නයට බොහෝ පිළිතුරු ලැබී ඇති නමුත් 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

අන්තර්ගත ආකාරයේ JSON

HTTP කේත

http_response_code

json_encode


ob_clean යොමුව සඳහා thnx. මට ප්‍රමුඛ පෙළක් තිබූ අතර එය මගේ ප්‍රතිචාරය ලබා ගත්තේය. Json () ඇමතුම්.
ක්‍රිස් ලව්


1

ඔබට අභිරුචි තොරතුරු යැවීමෙන් ජේසන් ලබා ගැනීමට අවශ්‍ය නම් ඔබට header('Content-Type: application/json');වෙනත් දෙයක් මුද්‍රණය කිරීමට පෙර මෙය එකතු කළ හැකිය , එබැවින් ඔබට ඔබේ පාරිභෝගිකයා මුද්‍රණය කළ හැකියecho '{"monto": "'.$monto[0]->valor.'","moneda":"'.$moneda[0]->nombre.'","simbolo":"'.$moneda[0]->simbolo.'"}';


1

ඔබ දත්ත සමුදායක් විමසා ප්‍රති J ල 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 භාවිතා කර ප්‍රති result ලය විග්‍රහ කිරීමට උදව් සඳහා මෙම නිබන්ධනය දෙස බලන්න .


1

පිරිමි ගැහැණු සහ පරිශීලක හැඳුනුම්පත ආපසු ලබා දීම සඳහා මෙය සරල PHP පිටපතක් වන අතර 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;
?>

JSON පෙළ සඳහා MIME මාධ්‍ය වර්ගය යෙදුම / json
AA

0

ඔබගේ ඩොමේන් වස්තු JSON වෙත සංයුති කිරීමට පහසු ක්‍රමයක් නම් මාෂල් අනුක්‍රමිකකරණය භාවිතා කිරීමයි . ඉන්පසු දත්ත වෙත json_encodeගොස් ඔබගේ අවශ්‍යතා සඳහා නිවැරදි අන්තර්ගත-වර්ගයේ ශීර්ෂයක් යවන්න. ඔබ සිම්ෆනි වැනි රාමුවක් භාවිතා කරන්නේ නම්, ශීර්ෂයන් අතින් සැකසීමට ඔබ සැලකිලිමත් විය යුතු නැත. එහිදී ඔබට JsonResponse භාවිතා කළ හැකිය .

උදාහරණයක් ලෙස ජාවාස්ක්‍රිප්ට් සමඟ ගනුදෙනු කිරීම සඳහා නිවැරදි අන්තර්ගත වර්ගය වනු ඇත 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);

0

ඔබ 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 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:

රූප විස්තරය මෙහි ඇතුළත් කරන්න


-1

ඔබට මෙම කුඩා 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();
?>
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.