ใครอยากทำ REST Services แบบผม คงจำเป็นจะต้องใช้มัน
เป็นวิธีง่ายๆ ที่จะแปลงค่าจาก Array เป็น XML และ/หรือ JSON ตามที่คุณต้องการ
สิ่งที่ต้องมีก่อนใช้งาน
(Requires PHP5.2.x or xmlwriter extension, json extension)
Example Array
<?
$data = array(
"php" => "good job",
"array" => "array assoc",
"example" => "easy",
"api" => array(
"xml" => "wow",
"json" => "shortly",
)
);
?>
Array Convert to XML
<?php
$xml = new XmlWriter();
$xml->openMemory();
$xml->startDocument('1.0', 'UTF-8'); //XML Encode
$xml->startElement('root'); // root data of XML
write($xml, $data);
$xml->endElement();
echo $xml->outputMemory(true);function write($xml, $data){
foreach($data as $key => $value){
if(is_array($value)){
$xml->startElement($key);
write($xml, $value);
$xml->endElement();
continue;
}
$xml->writeElement($key, $value);
}
}
?>
Array Convert to JSON
<?php
echo json_encode($data);
?>
ส่วนผลที่ได้คืออะไรไปลองทดสอบดูกันเองครับ
อ้างอิงจาก DZone Snippets
Leave a reply