Restituzione di JSON da uno script PHP


877

Voglio restituire JSON da uno script PHP.

Devo solo fare eco al risultato? Devo impostare l' Content-Typeintestazione?

Risposte:


1605

Mentre di solito stai bene senza di essa, puoi e dovresti impostare l'intestazione Content-Type:

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

Se non sto utilizzando un determinato framework, di solito consento ad alcuni parametri di richiesta di modificare il comportamento dell'output. Può essere utile, in genere per una rapida risoluzione dei problemi, non inviare un'intestazione o talvolta stampare_r il payload dei dati per osservarlo (sebbene nella maggior parte dei casi non dovrebbe essere necessario).


9
per ogni evenienza: dovresti usare i comandi header () solo in aggiunta al buffering dell'output per evitare avvisi "header già inviati"
Kevin

6
Il file php deve essere codificato in UTF-8 senza BOM :)
Krzysztof Kalinowski il

217
header('Content-type:application/json;charset=utf-8');
Timo Huovinen,

14
@mikepote In realtà non penso sia necessario avere il comando header nella parte superiore del file PHP. Se sputi inavvertitamente roba e questo fa scattare il tuo comando di intestazione, devi solo correggere il codice perché è rotto.
Halfstop,

8
@KrzysztofKalinowski no, il file PHP non deve essere codificato UTF-8. l'uscita DEVE essere codificata UTF-8. Queste affermazioni sbagliate non aiutano gli utenti non esperti a imparare come evitare che le cose si rompano, ma aiutano a far crescere miti su di loro e non imparare mai quale ruolo svolgono le codifiche sui flussi e come funzionano.
Áxel Costas Pena,

124

Un pezzo completo di codice PHP bello e chiaro che restituisce JSON è:

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

44

Secondo il manuale suljson_encode metodo può restituire una non stringa ( false ):

Restituisce una stringa codificata JSON in caso di esito positivo o FALSEnegativo.

Quando ciò accade, echo json_encode($data)viene generata la stringa vuota, che non è JSON valida .

json_encodeper esempio fallirà (e restituirà false) se il suo argomento contiene una stringa non UTF-8.

Questa condizione di errore dovrebbe essere acquisita in PHP, ad esempio in questo modo:

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

Quindi l'estremità ricevente dovrebbe ovviamente essere consapevole del fatto che la presenza della proprietà jsonError indica una condizione di errore, che dovrebbe trattare di conseguenza.

In modalità di produzione potrebbe essere meglio inviare solo uno stato di errore generico al client e registrare i messaggi di errore più specifici per un'indagine successiva.

Maggiori informazioni sulla gestione degli errori JSON nella documentazione di PHP .


2
Non ci sono charsetparametri per JSON; vedere la nota alla fine di tools.ietf.org/html/rfc8259#section-11 : "Nessun parametro 'charset' definito per questa registrazione. L'aggiunta di uno non ha alcun effetto sui destinatari conformi." (JSON deve essere trasmesso come UTF-8 per tools.ietf.org/html/rfc8259#section-8.1 , quindi specificare che è codificato come UTF-8 è un po 'ridondante.)
Patrick Dark

1
Grazie per averlo evidenziato, @PatrickDark. charsetParametro ridondante rimosso dalla stringa di intestazione HTTP.
trincot,

38

Prova json_encode per codificare i dati e impostare il tipo di contenuto con header('Content-type: application/json');.


15

Imposta il tipo di contenuto con, header('Content-type: application/json');quindi fai eco ai tuoi dati.


12

È anche utile impostare la sicurezza dell'accesso: basta sostituire * con il dominio che si desidera essere in grado di raggiungere.

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

Ecco altri esempi su questo: come bypassare Access-Control-Allow-Origin?


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

Qual è la differenza che indica il set di caratteri nell'intestazione? Per favore spiega, grazie.
Sanxofon,

6

Come detto sopra:

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

farà il lavoro. ma tieni presente che:

  • Ajax non avrà problemi a leggere json anche se questa intestazione non viene utilizzata, tranne se il tuo json contiene alcuni tag HTML. In questo caso è necessario impostare l'intestazione come application / json.

  • Assicurarsi che il file non sia codificato in UTF8-BOM. Questo formato aggiunge un carattere nella parte superiore del file, quindi la tua chiamata header () fallirà.


4

Una semplice funzione per restituire una risposta JSON con il codice di stato HTTP .

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_removee impostare esplicitamente la risposta http è una buona idea; sebbene l'impostazione dello stato e quindi http_response sembrino ridondanti. Potrebbe anche voler aggiungere una exitdichiarazione alla fine. Ho unito la funzione con @trincot 's: stackoverflow.com/a/35391449/339440
Stephen R

Grazie per il suggerimento Ho appena aggiornato la risposta.
Dan

3

La risposta alla tua domanda è qui ,

Dice.

Il tipo di supporto MIME per il testo JSON è application / json.

quindi se imposti l'intestazione su quel tipo e produci la tua stringa JSON, dovrebbe funzionare.


1

Sì, dovrai usare l'eco per visualizzare l'output. Mimetype: application / json


1

Se hai bisogno di ottenere json da php inviando informazioni personalizzate, puoi aggiungerle header('Content-Type: application/json');prima di stampare qualsiasi altra cosa, quindi puoi stampare su misuraecho '{"monto": "'.$monto[0]->valor.'","moneda":"'.$moneda[0]->nombre.'","simbolo":"'.$moneda[0]->simbolo.'"}';


1

Se si esegue una query su un database e è necessario il set di risultati in formato JSON, è possibile farlo in questo modo:

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

?>

Per assistenza nell'analisi del risultato utilizzando jQuery, dai un'occhiata a questo tutorial .


1

Questo è un semplice script PHP per restituire l'id maschio femminile e l'id utente come valore json sarà qualsiasi valore casuale mentre chiami lo script json.php.

Spero che questo aiuto, grazie

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

Il tipo di supporto MIME per il testo JSON è application / json
AA

0

Un modo semplice per formattare gli oggetti del tuo dominio su JSON è usare Marshal Serializer . Quindi passa i dati a json_encodee invia l'intestazione Content-Type corretta per le tue esigenze. Se stai usando un framework come Symfony, non devi occuparti di impostare manualmente le intestazioni. Lì puoi usare JsonResponse .

Ad esempio, sarebbe il Content-Type corretto per trattare con Javascript application/javascript.

O se hai bisogno di supportare alcuni browser piuttosto vecchi sarebbe il più sicuro text/javascript.

Per tutti gli altri scopi come un'app mobile, utilizzare application/jsoncome Content-Type.

Ecco un piccolo esempio:

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

Ogni volta che stai provando a restituire una risposta JSON per l'API, oppure assicurati di avere intestazioni adeguate e assicurati anche di restituire dati JSON validi.

Ecco lo script di esempio che ti aiuta a restituire la risposta JSON dall'array PHP o dal file JSON.

Script PHP (codice):

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

File JSON (DATI 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:

inserisci qui la descrizione dell'immagine


-1

Puoi usare questa piccola libreria PHP . Invia le intestazioni e ti dà un oggetto per usarlo facilmente.

Sembra :

<?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();
?>
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.