program tip

PHP 스크립트에서 JSON 반환

radiobox 2020. 9. 29. 07:32
반응형

PHP 스크립트에서 JSON 반환


PHP 스크립트에서 JSON을 반환하고 싶습니다.

결과를 에코 만하나요? Content-Type헤더 를 설정해야 합니까?


일반적으로 그것 없이는 괜찮지 만 Content-Type 헤더를 설정할 수 있고 설정해야합니다.

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

특정 프레임 워크를 사용하지 않는 경우 일반적으로 일부 요청 매개 변수가 출력 동작을 수정하도록 허용합니다. 일반적으로 빠른 문제 해결을 위해 헤더를 보내지 않거나 때로는 데이터 페이로드를 print_r하여 눈에 띄게하는 것이 유용 할 수 있습니다 (대부분의 경우에는 필요하지 않음).


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

메서드 설명서에json_encode 따르면 문자열이 아닌 ( false )을 반환 할 수 있습니다 .

성공 또는 FALSE실패시 JSON 인코딩 문자열을 반환합니다 .

이 경우 잘못된 JSON 인echo json_encode($data) 빈 문자열이 출력됩니다 .

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(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 오류 처리에 대해 자세히 알아보세요 .


시도 로 json_encode를 데이터를 인코딩와 콘텐츠 형식을 설정합니다 header('Content-type: application/json');.


콘텐츠 유형을 설정 한 header('Content-type: application/json');다음 데이터를 에코합니다.


액세스 보안을 설정하는 것도 좋습니다. *를 도달 할 수있는 도메인으로 바꾸면됩니다.

<?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을 우회하는 방법?


위에서 말했듯이 :

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

일을 할 것입니다. 그러나 다음 사항을 명심하십시오.

  • Ajax는이 헤더를 사용하지 않더라도 json에 HTML 태그가 포함되어있는 경우를 제외하고는 json을 읽는 데 문제가 없습니다. 이 경우 헤더를 application / json으로 설정해야합니다.

  • 파일이 UTF8-BOM으로 인코딩되지 않았는지 확인하십시오. 이 형식은 파일 상단에 문자를 추가하므로 header () 호출이 실패합니다.


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

귀하의 질문에 대한 답변 은 여기에 있습니다 .

그것은 말한다.

JSON 텍스트의 MIME 미디어 유형은 application / json입니다.

따라서 헤더를 해당 유형으로 설정하고 JSON 문자열을 출력하면 작동합니다.


예, 출력을 표시하려면 echo를 사용해야합니다. MIME 유형 : application / json


사용자 정의 정보를 보내는 PHP에서 json을 가져와야 header('Content-Type: application/json');하는 경우 다른 것을 인쇄하기 전에 이것을 추가 할 수 있으므로 사용자 정의 를 인쇄 할 수 있습니다.echo '{"monto": "'.$monto[0]->valor.'","moneda":"'.$moneda[0]->nombre.'","simbolo":"'.$moneda[0]->simbolo.'"}';


이것은 json.php 스크립트를 호출 할 때 임의의 값이 될 json 값으로 남성 여성과 사용자 ID를 반환하는 간단한 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;
?>

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

데이터베이스를 쿼리하고 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를 사용하여 결과를 구문 분석하는 데 도움 이 필요하면이 자습서를 참조하십시오 .


도메인 객체를 JSON으로 포맷하는 쉬운 방법은 Marshal Serializer 를 사용하는 것 입니다. 그런 다음 데이터를 전달하고 json_encode필요에 맞는 올바른 Content-Type 헤더를 보냅니다. Symfony와 같은 프레임 워크를 사용하는 경우 헤더를 수동으로 설정할 필요가 없습니다. 거기에서 JsonResponse를 사용할 수 있습니다 .

예를 들어 Javascript를 처리하기위한 올바른 Content-Type은 application/javascript.

또는 꽤 오래된 브라우저를 지원해야하는 경우 가장 안전한 방법이 있습니다 text/javascript.

모바일 앱과 같은 다른 모든 목적을 위해 application/jsonContent-Type으로 사용합니다.

다음은 작은 예입니다.

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

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

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 :

여기에 이미지 설명 입력

참고 URL : https://stackoverflow.com/questions/4064444/returning-json-from-a-php-script

반응형