Skip to content

emka.web.id

menulis pengetahuan – merekam peradaban

Menu
  • Home
  • Tutorial
  • Makalah
  • Ke-NU-an
  • Kabar
  • Search
Menu

Belajar PHP: Konversi JSON – XML – Array – String

Posted on February 2, 2012

Tutorial kali ini akan membahas konversi antar 3 data interchange yang populer, yaitu JSON, XML dan Array. Untuk library konversi ini, gunakan salah satu library buatan om Rochak Chauchan dari India yang dipublish pada PHPClasses.org.

Untuk file librarynya, kurang lebih sebagai berikut:
[sourcecode language=”php”]
<?php
define("NODE_SEPERATOR","#*#");
define("LINE_SEPERATOR","!#=#!");
define("ERROR_STYLE","color:#fff;background-color:#ff0000;font-weight:bold;padding:5px;margin:5px;");

/**
* This class interchange String, XML, JSON and Array into each other.
*
* @author Rochak Chauhan
* @package PhpJsonXmlArrayStringInterchanger
* @version beta
*/
class PhpJsonXmlArrayStringInterchanger{
private $errorLog=array();

/**
* Function to display last error for debugging purpose
*
* @access public
* @return string
*/
public function displayLastError(){
$return="No errors were encountered.";
$c=count($this->errorLog);
if($c>0){
$i=$c-1;
$return="<div style=’".ERROR_STYLE."’>".$this->errorLog[$i]."</div>";
}
echo $return;
}

/**
* Function to display complete error log for debugging purpose
*
* @access public
* @return string
*/
public function displayErrorLog(){
$return="No errors were encountered.";
$c=count($this->errorLog);
if($c>0){
$return="";
for($i=0;$i<$c;$i++){
$return.="<div style=’".ERROR_STYLE."’>".$this->errorLog[$i]."</div>";
}
}
echo $return;
}

/**
* Function to recursivly parse Xml Content
*
* @param mixed $ret
* @access private
* @return array on success and false on failure
*/
private function parseXml($ret) {
$return=false;
if(is_object($ret)){
$ret=(array)$ret;
$this->parseXml($ret);
}
if(is_array($ret)){
foreach($ret as $k=>$v){
if(is_object($v)){
$return[$k]=$this->parseXml($v);
}
else {
$return[$k]=$v ;
}
}
}
return $return;
}

/**
* Function to convert XML into Array
*
* @param string $xmlContent
* @access public
* @return array on success and false on failure
*/
public function convertXmlToArray($xmlContent){
$return=false;
$ret=simplexml_load_string($xmlContent);
if($ret===false){
$this->errorLog[]="Invalid XML content: $xmlContent in function: ".__FUNCTION__." on line: ".__LINE__." in filename= ".__FILE__;
return false;
}
else{
$return=$this->parseXml($ret);
if($return===false){
$this->errorLog[]="Failed to parse XML content in function: ".__FUNCTION__." on line: ".__LINE__." in filename= ".__FILE__;
return false;
}
}
return $return;
}

/**
* Function to recursivly parse Array Content
*
* @param mixed $ret
* @access private
* @return string(xml) on success and false on failure
*/
private function parseArray($array) {
if(is_array($array)){
foreach($array as $k=>$v){
if(trim($k)==""){
$this->errorLog[]="Array needs to be associative as parameter in function: ".__FUNCTION__." on line: ".__LINE__." in filename= ".__FILE__;
return false;
}
else{
if (is_numeric($k)) {
$k="nodeValue$k";
}
if(is_array($v)){
$return.="<$k>".$this->parseArray($v)."</$k>";
}
else {
$return.="<$k>$v</$k>";
}
}
}
}
else{
$this->errorLog[]="Invalid array in function: ".__FUNCTION__." on line: ".__LINE__." in filename= ".__FILE__;
return false;
}
return $return;
}

/**
* Function to convert an associative array into XML
*
* @param string $array
* @access public
* @return string(xml) on success and false on failure
*/
public function convertArrayToXML($array){
$return="<?xml version=’1.0′ encoding=’ISO-8859-1′?><PhpJsonXmlArrayStringInterchanger>";
$return.=$this->parseArray($array);
$return.="</PhpJsonXmlArrayStringInterchanger>";
return $return;
}

/**
* Function to convert an JSON into XML
*
* @param string $json
* @access public
* @return string(xml) on success and false on failure
*/
public function convertJsonToXML($json){
if(!is_string($json)){
$this->errorLog[]="The first parameter should to be string in function: ".__FUNCTION__." on line: ".__LINE__." in filename= ".__FILE__;
return false;
}
$array=json_decode($json,true);
if($array===false){
$this->errorLog[]="Failed to decode JSON in function: ".__FUNCTION__." on line: ".__LINE__." in filename= ".__FILE__;
return false;
}
else{
return $this->convertArrayToXML($array);
}
}

/**
* Function to convert an JSON into array
*
* @param string $json
* @access public
* @return array on success and false on failure
*/
public function convertJsonToArray($json){
if(!is_string($json)){
$this->errorLog[]="The first parameter should to be string in function: ".__FUNCTION__." on line: ".__LINE__." in filename= ".__FILE__;
return false;
}
$array=json_decode($json,true);
if($array===false){
$this->errorLog[]="Failed to decode JSON in function: ".__FUNCTION__." on line: ".__LINE__." in filename= ".__FILE__;
return false;
}
else{
return $array;
}
}

/**
* Function to parse String and convert it into array
*
* @param array $array
* @access public
* @return array on success and false on failure
* @todo refactor the code from line 205-222 (automate it)
*/
public function convertStringToArray($string,&$myarray=""){
$lines = explode(LINE_SEPERATOR,$string);
foreach ($lines as $value){
$items = explode(NODE_SEPERATOR,$value);
if (sizeof($items) == 2){
$myarray[$items[0]] = $items[1];
}
elseif (sizeof($items) == 3){
$myarray[$items[0]][$items[1]] = $items[2];
}
elseif (sizeof($items) == 4){
$myarray[$items[0]][$items[1]] [$items[2]] = $items[3];
}
elseif (sizeof($items) == 5){
$myarray[$items[0]][$items[1]] [$items[2]][$items[3]] = $items[4];
}
elseif (sizeof($items) == 6){
$myarray[$items[0]][$items[1]] [$items[2]][$items[3]][$items[4]] = $items[5];
}
elseif (sizeof($items) == 7){
$myarray[$items[0]][$items[1]] [$items[2]][$items[3]][$items[4]][$items[5]] = $items[6];
}
}
return $myarray;
}

/**
* Function to parse Array and convert it into string
*
* @param array $array
* @access private
* @return string on success and false on failure
*/
private function convertArrayToString($myarray,&$output="",&$parentkey=""){
if(is_array($myarray)){
if (trim($parentkey)=="") {
$parentkey=LINE_SEPERATOR;
}
foreach($myarray as $key=>$value){
if (is_array($value)) {
$parentkey .= $key.NODE_SEPERATOR;
$this->convertArrayToString($value,$output,$parentkey);
$parentkey = "";
}
else {
$output .= $parentkey.$key.NODE_SEPERATOR.$value.LINE_SEPERATOR;
}
}
}
else{
$this->errorLog[]="Invalid array in function: ".__FUNCTION__." on line: ".__LINE__." in filename= ".__FILE__;
return false;
}
return $output;
}

/**
* Function to convert XML into string
*
* @param string $xml
* @return string on success and false on failure
*/
public function convertXmltoString($xml){
$array=$this->convertXmlToArray($xml);
if ($array===false) {
return false;
}
else {
return $this->convertArrayToString($array);
}
}
}
?>
[/sourcecode]

Contoh Penerapan

Contoh data kasar (json, xml, dan array):
[sourcecode language=”php”]
<?php
$sampleXml='<?xml version="1.0" encoding="ISO-8859-1"?>
<mainNode>
<node1>
<FirstName>First Name1</FirstName>
<LastName>Last Name1</LastName>
<Misc>
<sample1>A1</sample1>
<sample2>A2</sample2>
</Misc>
</node1>
<node2>
<FirstName>First Name2</FirstName>
<LastName>Last Name2</LastName>
<Misc>
<sample1>B1</sample1>
<sample2>B2</sample2>
</Misc>
</node2>
<node3>
<FirstName>First Name3</FirstName>
<LastName>Last Name3</LastName>
<Misc>
<sample1>C1</sample1>
<sample2>C2</sample2>
</Misc>
</node3>
</mainNode>’;

$sampleArray=array(
‘node1’=>array("abc"=>1234),
‘node2’=>array("xyz"=>9876)
);

$sampleJson='{"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}}’;

$sampleString="!#=#!node1#*#FirstName#*#First Name1!#=#!!#=#!node1#*#LastName#*#Last Name1!#=#!!#=#!node1#*#Misc#*#sample1#*#A1!#=#!!#=#!node1#*#Misc#*#sample2#*#A2!#=#!node2#*#FirstName#*#First Name2!#=#!node2#*#LastName#*#Last Name2!#=#!node2#*#Misc#*#sample1#*#B1!#=#!node2#*#Misc#*#sample2#*#B2!#=#!node3#*#FirstName#*#First Name3!#=#!node3#*#LastName#*#Last Name3!#=#!node3#*#Misc#*#sample1#*#C1!#=#!node3#*#Misc#*#sample2#*#C2!#=#!";

//Create class object
require_once("PhpJsonXmlArrayStringInterchanger.inc.php");
$object=new PhpJsonXmlArrayStringInterchanger();
?>
[/sourcecode]

Konversi XML ke Array

[sourcecode language=”php”]
//XML to Array
$array=$object->convertXmltoArray($sampleXml);
if($array===false){
//$object->displayErrorLog();
$object->displayLastError();
}
else{
echo "<pre>";
print_r($array);
exit;
}
[/sourcecode]

Konversi Array ke XML

[sourcecode language=”php”]
// Array to xml
$xml=$object->convertArrayToXML($sampleArray);
if($xml===false){
//$object->displayErrorLog();
$object->displayLastError();
}
else{
header("content-type: text/xml");
echo $xml;
exit;
}
[/sourcecode]

Konversi JSON ke XML

[sourcecode language=”php”]
// JSON to xml
$xml=$object->convertJsonToXML($sampleJson);
if($xml===false){
//$object->displayErrorLog();
$object->displayLastError();
}
else{
header("content-type: text/xml");
echo $xml;
exit;
}
[/sourcecode]

Konversi JSON ke Array

[sourcecode language=”php”]
// JSON to array
$array=$object->convertJsonToArray($sampleJson);
if($array===false){
//$object->displayErrorLog();
$object->displayLastError();
}
else{
echo "<pre>";
print_r($array);
exit;
}
[/sourcecode]

Konversi XML ke String

[sourcecode language=”php”]
//XML to String
$string=$object->convertXmltoString($sampleXml);
if($string===false){
//$object->displayErrorLog();
$object->displayLastError();
}
else{
echo $string;exit;
}
[/sourcecode]

Konversi String ke Array

[sourcecode language=”php”]
//String to Array
$array=$object->convertStringToArray($sampleString);
if($array===false){
//$object->displayErrorLog();
$object->displayLastError();
}
else{
echo "<pre>";
print_r($array);
}
[/sourcecode]

Bagaimana dengan contoh diatas? mudah kan mengkonversi antar tipe data dengan PHP dan library ini?. Selamat mencoba.

Terbaru

  • Cara Memperbaiki Error ScanPST.exe dan File PST di Microsoft Outlook
  • Cara Mengatasi Error DWMAPI.DLL is either not designed or not found
  • Cara Memperbaiki Error Equation/Rumus Jelek di Microsoft Word
  • Cara Mengatasi Adapter Jaringan VMware yang Hilang di Windows 11
  • Cara Reset Multi-Factor Authentication (MFA) di Microsoft Entra
  • Cara Mengatasi Masalah Konektivitas VM Hyper-V ke Host
  • Cara Memperbaiki Error 0x8000FFFF Catastrophic Failure Saat Ekstrak Zip
  • Cara Memperbaiki File Explorer Crash Saat Membuka Folder Besar di Windows 11/10
  • Cara Mengatasi Error Login 0x8007003B di Outlook, Microsoft, XBox dll
  • Cara Memulihkan Akun Admin Microsoft 365 Karena MFA Gagal
  • Cara Mengatasi Error “A Conexant audio device could not be found”
  • Cara Memperbaiki Windows Tidak Nyala Lagi Setelah Sleep/Locked
  • Cara Memperbaiki Komputer Crash karena Discord
  • Cara Memperbaiki Error Windows “Failed to update the system registry”
  • Cara Memperaiki LGPO/exe/g
  • Cara Memperbaiki Error Tidak bisa Add Calendar di Outlook
  • Cara Memperbaiki File Transfer Drop ke 0 di Windows 11
  • Cara Memperbaiki Microsoft Copilot Error di Outlook
  • Cara Memperbaiki Error Virtualbox NtCreateFile(\Device\VBoxDrvStub) failed, Not signed with the build certificate
  • Cara Memperbaiki Error “the system detected an address conflict for an IP address, with Event ID 4199”
  • Cara Memperbaiki Password Microsoft Edge yang Hilang
  • Cara Memperbaiki Email Outlook yang Hilang atau Tidak Muncul
  • Cara Menemukan Username dan Password di Windows 11
  • Cara Mengatasi Error Virtualbox not detecting Graphics Card di Windows 11
  • Cara Mengatasi Error Windows MFReadWrite.dll not found or missing
  • Cara Membuat Formulir Menggunakan Zoho Form
  • Pemerintah Ganti Ujian Kesetaraan Dengan TKA 2025
  • Ini Perbedaan TKA vs Ujian Nasional: TKA Lebih Sakti?
  • Daftar TKA Tutup 5 Oktober: Sudah 3.3 Juta Yang Daftar
  • Review Aplikasi ClipClaps: Penipuan atau Tidak?
  • Cara Memperbaiki Error ScanPST.exe dan File PST di Microsoft Outlook
  • Cara Mengatasi Error DWMAPI.DLL is either not designed or not found
  • Cara Memperbaiki Error Equation/Rumus Jelek di Microsoft Word

©2025 emka.web.id | Design: Newspaperly WordPress Theme