2010年4月21日水曜日

PHPで走るRDF/XMLの差分アイテムを取得する関数

あるプログラムで RDF/XML の更新部分を抜き出すプログラムが必要だったので作成。
diff_rdfの
  第一引数には最新版のRDFのファイル名を、
  第二引数には古い版のRDFのファイル名を
入れてください。

<?php
/**********************************************************
* diff_rdf
* @poochin - http://www13.atpages.jp/llan/
* LastUpdate: 2010-04-21
*
* License: MIT or new BSD
*********************************************************/

/**
* diff_rdf
*   get newer entry!
*   ja(新しいエントリーを取得!)
*
* Argument
*   file1 -- new rdf file name
*   file2 -- old rdf file name
*   ja(file1 -- 新しいRDFファイル)
*   ja(file2 -- 古いRDFファイル)
*
* return
*   difference items as array
*   ja(差分のitemを配列にして返す)
*/
function diff_rdf($file1, $file2)
{
 /**
  * to compare rdf:li, parse and pick out file1, file2
  * ja(items > rdf:li を比較する為に file1, file2 を展開する)
  */
 $xml1 = simplexml_load_file($file1);
 $namespaces1 = $xml1->getNamespaces();
 $list1 = current($xml1->xpath('//rdf:Seq'))->children($namespaces1['rdf'])->li;
 $list1_array = asXMLinArray_($list1);
 $items1 = getLists_($xml1->item);

 $xml2 = simplexml_load_file($file2);
 $namespaces2 = $xml2->getNamespaces();
 $list2 = current($xml2->xpath('//rdf:Seq'))->children($namespaces2['rdf'])->li;
 $list2_array = asXMLinArray_($list2);
 // $items2 = getLists_($xml2->item); // items2 isn't neccesary

 // get different
 // ja(差分を取得)
 $diff = array_diff($list1_array, $list2_array);

 // returning array, use diff's key to get items of file1
 // 差分のキーと共通する items1 を返す
 return array_intersect_key($items1, $diff);
}

/**
* getLists(simpleXML-Object)
*
*   using installation, loop and get all xml children.
*
*   ja(イタレーションを利用してsimpleXMLオブジェクト の
* 配列を取得する)
*/
function getLists_($xml_list)
{
 $lists = array();
 foreach ($xml_list as $item) {
   $lists[] = $item;
 }
 return $lists;
}

/**
* asXMLinArray(Array include simpleXML-Object)
*
*   xml children to Array using asXML()
*
*   ja(simpleXMLの子要素に asXML() をかけて配列にする)
*/
function asXMLinArray_($xml_array)
{
 $lists = array();
 foreach ($xml_array as $item) {
   $lists[] = $item->asXML();
 }
 return $lists;
}


/*---------------------------------------------------------
                         Sample Code
---------------------------------------------------------*/
$f1 = 'test1.rdf.xml';
$f2 = 'test2.rdf.xml';
print_r(diff_rdf ($f1, $f2));

多分このコードだけで使い方は分かるんじゃないかな、と思います。

変更2010-04-21:

複数 diff_rdf を呼び出すと、関数の再定義が行われてしまうという問題を抱えていたので習性

追伸2010-10-10:

更新したものを github にあげました [github.com]

0 件のコメント:

コメントを投稿