2009-05-13 13 views
40

c'è un modo per convertire json in xml in PHP? So che xml to json è molto possibile.C'è un modo per convertire json in xml in PHP?

+0

E ancora più importante: perché mai vorresti farlo? – NikiC

+1

'$ xml =" ";' (Fai una domanda stupida ...) – salathe

+0

Zend Framework ha un ottimo componente [componente] (http://framework.zend.com /manual/en/zend.json.xml2json.html) per questo. – markus

risposta

11

Dipende da come esattamente si desidera che l'XML sia. Vorrei provare una combinazione di json_decode() e PEAR::XML_Serializer (more info and examples on sitepoint.com).

require_once 'XML/Serializer.php'; 

$data = json_decode($json, true) 

// An array of serializer options 
$serializer_options = array (
    'addDecl' => TRUE, 
    'encoding' => 'ISO-8859-1', 
    'indent' => ' ', 
    'rootName' => 'json', 
    'mode' => 'simplexml' 
); 

$Serializer = &new XML_Serializer($serializer_options); 
$status = $Serializer->serialize($data); 

if (PEAR::isError($status)) die($status->getMessage()); 

echo '<pre>'; 
echo htmlspecialchars($Serializer->getSerializedData()); 
echo '</pre>'; 

(codice non testato - ma si ottiene l'idea)

+0

Ack, mi hai battuto di mezzo minuto.Lascerò comunque il mio - è un approccio leggermente diverso. –

25

Se siete disposti a utilizzare il XML Serializer dal PEAR, è possibile convertire il JSON in un oggetto PHP e quindi l'oggetto PHP per XML in due semplici passaggi:

include("XML/Serializer.php"); 

function json_to_xml($json) { 
    $serializer = new XML_Serializer(); 
    $obj = json_decode($json); 

    if ($serializer->serialize($obj)) { 
     return $serializer->getSerializedData(); 
    } 
    else { 
     return null; 
    } 
} 
7

Crack aprire l'JSON con json_decode, e attraversarla per generare qualunque XML che si desidera.

Nel caso ve lo stiate chiedendo, non esiste un mapping canonico tra JSON e XML, quindi è necessario scrivere il codice di generazione XML autonomamente, in base alle esigenze dell'applicazione.

5

ho unito le due proposte precedenti in:

/** 
* Convert JSON to XML 
* @param string - json 
* @return string - XML 
*/ 
function json_to_xml($json) 
{ 
    include_once("XML/Serializer.php"); 

    $options = array (
     'addDecl' => TRUE, 
     'encoding' => 'UTF-8', 
     'indent' => ' ', 
     'rootName' => 'json', 
     'mode' => 'simplexml' 
    ); 

    $serializer = new XML_Serializer($options); 
    $obj = json_decode($json); 
    if ($serializer->serialize($obj)) { 
     return $serializer->getSerializedData(); 
    } else { 
     return null; 
    } 
} 
+0

Perfetto per me Cheers – wired00

4

Un approch nativo potrebbe essere

function json_to_xml($obj){ 
    $str = ""; 
    if(is_null($obj)) 
    return "<null/>"; 
    elseif(is_array($obj)) { 
     //a list is a hash with 'simple' incremental keys 
    $is_list = array_keys($obj) == array_keys(array_values($obj)); 
    if(!$is_list) { 
     $str.= "<hash>"; 
     foreach($obj as $k=>$v) 
     $str.="<item key=\"$k\">".json_to_xml($v)."</item>".CRLF; 
     $str .= "</hash>"; 
    } else { 
     $str.= "<list>"; 
     foreach($obj as $v) 
     $str.="<item>".json_to_xml($v)."</item>".CRLF; 
     $str .= "</list>"; 
    } 
    return $str; 
    } elseif(is_string($obj)) { 
    return htmlspecialchars($obj) != $obj ? "<![CDATA[$obj]]>" : $obj; 
    } elseif(is_scalar($obj)) 
    return $obj; 
    else 
    throw new Exception("Unsupported type $obj"); 
} 
+0

Bel copione, grazie. – Zsolti

1

Un'altra opzione sarebbe quella di utilizzare un JSON streaming parser.

L'uso di un parser dello streamer sarebbe utile se si desidera ignorare il grafico dell'oggetto intermedio creato da PHP quando si utilizza json_decode. Ad esempio, quando si dispone di un documento JSON di grandi dimensioni e la memoria è un problema, è possibile generare l'XML con XMLWriter direttamente durante la lettura del documento con il parser di streaming.

Un esempio potrebbe essere https://github.com/salsify/jsonstreamingparser

$writer = new XMLWriter; 
$xml->openURI('file.xml'); 
$listener = new JSON2XML($writer); // you need to write the JSON2XML listener 
$stream = fopen('doc.json', 'r'); 
try { 
    $parser = new JsonStreamingParser_Parser($stream, $listener); 
    $parser->parse(); 
} catch (Exception $e) { 
    fclose($stream); 
    throw $e; 
} 

Il JSON2XML Listener avrebbe bisogno di attuare il Listener interface:

interface JsonStreamingParser_Listener 
{ 
    public function start_document(); 
    public function end_document(); 
    public function start_object(); 
    public function end_object(); 
    public function start_array(); 
    public function end_array(); 
    public function key($key); 
    public function value($value); 
} 

In fase di esecuzione, l'ascoltatore riceverà i vari eventi dal parser, per esempio quando il parser trova un oggetto, invierà i dati al metodo start_object(). Quando trova un array, attiverà start_array() e così via. In questi metodi, devi delegare i valori ai metodi appropriati in XMLWriter, ad es. start_element() e così via.

Disclaimer: Non sono affiliato con l'autore, né ho usato lo strumento prima. Ho scelto questa libreria perché l'API sembrava abbastanza semplice da illustrare come utilizzare un parser JSON basato su eventi.

Problemi correlati