Skip to content

Instantly share code, notes, and snippets.

@katsuobushiFPGA
Last active June 1, 2017 14:54
Show Gist options
  • Save katsuobushiFPGA/8f74b5e1c6b9f6ca497f99facf023b8e to your computer and use it in GitHub Desktop.
Save katsuobushiFPGA/8f74b5e1c6b9f6ca497f99facf023b8e to your computer and use it in GitHub Desktop.
<?php
class SimpleXMLExtended extends SimpleXMLElement
{
public function addCData($cdata_text)
{
$node= dom_import_simplexml($this);
$no = $node->ownerDocument;
$node->appendChild($no->createCDATASection($cdata_text));
}
}
//
//second_node 1つのみ
$pub_info = [
'publisher' => "publisher",
'publisherurl' => "https://publisherurl.com",
'lastBuildDate' => gmdate("D, d M Y G:i:s T"),
];
//求人ノード
// <job> ~ </job>でくくる必要がある
$job_info = [
'title' => '',
'date' => '',
'referencenumber' => '',
'url' => '',
'company' => '',
'station' => '',
'city' => '',
'state' => '',
'country' => '',
'description' => '',
'salary' => '',
'jobtype' => '',
'category' => ''
];
//Main
$job_count = 0;//job数
$root = '<?xml version="1.0" encoding="UTF-8" ?><source></source>';
$rootNode = new SimpleXMLExtended($root);
//publishNode作成
createPubNode($rootNode, $pub_info);
$job_ary [] = $job_info;
//jobNode作成
foreach($job_ary as $job) {
createJobNode($rootNode, $job);
}
$xml = shapingXML($rootNode);
echo $xml;
/***
* 関数群
*/
function createPubNode(&$rootNode, $pub_info) {
foreach($pub_info as $key=>$value) {
$itemNode = $rootNode->addChild($key,_h($value));
}
}
function createJobNode(&$rootNode, $job_info) {
foreach($job_info as $key=>$value) {
if(empty($value)) {
continue;
}
$itemNode = $rootNode->addChild($key);
$itemNode->addCData(_h($value));
}
}
function shapingXML($xml) {
$dom = new DOMDocument('1.0', 'utf-8');
$dom->loadXML($xml->asXML());
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
return $dom->saveXML();
}
/**
* エスケープ処理
* XMLの値の中に&が入ってるとエラーで落ちるので
*/
function _h($value)
{
return htmlspecialchars($value, ENT_QUOTES);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment