「PHP入門」SimpleXMLでxmlドキュメントを作成するサンプル

PHPコード:
<?PHP
$bookArr = array(
array(
'title’ => 'how to study spring mvc’,
'content’ => 'spring mvc development and sample’,
'pubdate’ => '2016-10-11’,
),
array(
'title’ => 'struts2 begin learning’,
'content’ => 'Struts2 sample and grammar’,
'pubdate’ => '2015-01-11’,
)
);

// 配列
$propArr = array(
'title’ => array(
'size’ => 1
)
);

$strXml = <<<XML
<?xml version=’1.0′ encoding=’utf-8′?>
<article>
</article>
XML;

$xml = simplexml_load_string($strXml);

foreach ($bookArr as $data) {
$item = $xml->addChild('item’);
if (is_array($data)) {
foreach ($data as $key => $row) {
$node = $item->addChild($key, $row);

if (isset($propArr[$key]) && is_array($propArr[$key])) {
// foreachループ
foreach ($propArr[$key] as $akey => $aval) {
$node->addAttribute($akey, $aval);
}
}
}
}
}
echo $xml->asXML();
?>

PHP

Posted by arkgame