2008년 1월 10일 목요일

[xml] in php

xml sample
<?xml version="1.0" encoding="UTF-8"?>
<employees>
<employee id="345435">
<name>John Smith</name>
</employee>
</employees>
xml_decode
<?php

// The raw post body is available in the variable $HTTP_RAW_POST_DATA
$employees = xml_decode($HTTP_RAW_POST_DATA);

// Get the employee element
$employee = $employees->employee[0];

// Get the id attribute
$id = $employee['id'];

// Get the name
$name = $employee->name->toString();

?>


xml_encode
$var = array('name' => "Smith", 'address' => array('line1' => 'This lane', 'line2' => 'Somewhere'));
echo xml_encode($var,  "employee");


xml_encode source
function xml_encode($array, $indent=false, $i=0) {
if(!$i) {
$data = '<?xml version="1.0"?>'.($indent?"\r\n":'').'<root>'.($indent?"\r\n":'');
} else {
$data = '';
}

foreach($array as $k => $v) {
if(is_numeric($k)) {
$k = 'item';
}

$data .= ($indent?str_repeat("\t", $i):'').'<'.$k.'>';

if(is_array($v)) {
$data .= ($indent?"\r\n":'').xml_encode($v, $indent, ($i + 1)).($indent?str_repeat("\t", $i):'');
} else {
$data .= $v;
}

$data .= '</'.$k.'>'.($indent?"\r\n":'');
}

if(!$i) {
$data .= '</root>';
}

return $data;






댓글 없음:

댓글 쓰기