Belajar PHP: Konversi JSON – XML – Array – String

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:

<?php 
define("NODE_SEPERATOR","#*#"); 
define("LINE_SEPERATOR","!#=#!"); 
define("ERROR_STYLE","color:#fff;background-color:#ff0000;font-weight:bold;padding:5px;margin:5px;"); 

 
class PhpJsonXmlArrayStringInterchanger{ 
    private $errorLog=array(); 

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

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

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

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

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

     
    public function convertArrayToXML($array){ 
        $return="<?xml version='1.0' encoding='ISO-8859-1'?><PhpJsonXmlArrayStringInterchanger>"; 
        $return.=$this->parseArray($array); 
        $return.="</PhpJsonXmlArrayStringInterchanger>"; 
        return $return; 
    } 

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

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


     
    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; 
    } 
     
     
    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; 
    } 
     
     
    public function convertXmltoString($xml){ 
        $array=$this->convertXmlToArray($xml); 
        if ($array===false) { 
            return false; 
        } 
        else { 
            return $this->convertArrayToString($array); 
        } 
    } 
} 
?>

Contoh Penerapan

Contoh data kasar (json, xml, dan array):

<?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!#=#!";


require_once("PhpJsonXmlArrayStringInterchanger.inc.php"); 
$object=new PhpJsonXmlArrayStringInterchanger(); 
?>

Konversi XML ke Array

$array=$object->convertXmltoArray($sampleXml); 
if($array===false){ 
    
    $object->displayLastError(); 
} 
else{ 
    echo "<pre>"; 
    print_r($array); 
    exit; 
} 

Konversi Array ke XML

 

$xml=$object->convertArrayToXML($sampleArray); 
if($xml===false){ 
    
    $object->displayLastError(); 
} 
else{ 
    header("content-type: text/xml"); 
    echo $xml;  
    exit; 
} 

Konversi JSON ke XML

$xml=$object->convertJsonToXML($sampleJson); 
if($xml===false){ 
    
    $object->displayLastError(); 
} 
else{ 
    header("content-type: text/xml"); 
    echo $xml;  
    exit; 
} 

Konversi JSON ke Array

$array=$object->convertJsonToArray($sampleJson); 
if($array===false){ 
    
    $object->displayLastError(); 
} 
else{ 
    echo "<pre>"; 
    print_r($array); 
    exit; 
} 

Konversi XML ke String

$string=$object->convertXmltoString($sampleXml); 
if($string===false){ 
    
    $object->displayLastError(); 
} 
else{ 
    echo $string;exit; 
} 

Konversi String ke Array

$array=$object->convertStringToArray($sampleString); 
if($array===false){ 
    
    $object->displayLastError(); 
} 
else{ 
    echo "<pre>"; 
    print_r($array); 
} 

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

Wagiman Wiryosukiro

Petani Sistem Informasi, tukang las plugin & themes Wordpress. Co-Founder SistemInformasi.biz. Saat ini aktif sebagai Developer & kontributor di OpenMandriva Linux.

You may also like...

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: