用PHP寫的一個文本處理小程序

以前用Python寫了一個處理SQL文件的小程序,今天也同樣碰到了一個類似的要求,不過處理的對象是PHP文件,於是就用PHP寫了一個處理程序。

問題的描述如下:被處理的文件的文件名類似於{$channel_id}_{$category_id}.php,所有文件內都包含一個Array變量,文件結構類似於下面:

<?php

$arrLeftMoreInfo = array (

    '0' => array (

        'name' => 'Laptop Blog',

        'url' => 'http://blogs.smarter.com/gadgets/category/laptops/',

        'icon' => 'icon_leftmoreinfo.gif',

        'type' => 'Review'

    ),

    '1' => array (

        'name' => 'How Laptops Work',

        'url' => 'http://communication.howstuffworks.com/laptop.htm',

        'icon' => 'icon_leftmoreinfo.gif',

        'type' => 'Review'

    ),

    '2' => array (

        'name' => 'Laptop Magazine',

        'url' => 'http://www.laptopmag.com/',

        'icon' => 'icon_leftmoreinfo.gif',

        'type' => 'Review'

    )

);

?>



現在的要求就是生成一個SQL文件,裏面的內容就是對應表的數據插入語句。所以生成的SQL語句看起來應該類似於這個樣子:

INSERT INTO `sit_seomoreinfo` 

(`id`,`ChannelID`,`CategoryID`,`name`,`url`,`icon`,`type`,`created`,`modified`) 

VALUES 

(null,2,31,'Laptop Blog','http://blogs.smarter.com/gadgets/category/laptops/','icon_leftmoreinfo.gif','Review',now(),now()),

(null,2,31,'How Laptops Work','http://communication.howstuffworks.com/laptop.htm','icon_leftmoreinfo.gif','Review',now(),now()),

(null,2,31,'Laptop Magazine','http://www.laptopmag.com/','icon_leftmoreinfo.gif','Review',now(),now()),

……

  最終的代碼就是下面這個樣子:  

<?php

$curDir = dirname(__FILE__);

$dh = opendir($curDir);

$i = 0;

$sqlArray = array ();

while ($file = readdir($dh)) {

    if ($file != '.' && $file != '..' && preg_match("/^([0-9]+)_([0-9]+)/.php$/", $file, $name)) {

        require $file;

        foreach ($arrLeftMoreInfo as $k => $v) {

            $i++;

            $sqlArray[] = "(null,{$name[1]},{$name[2]},'{$v['name']}','{$v['url']}','{$v['icon']}','{$v['type']}',now(),now())";

        }

    }

}

closedir($dh);

$sqlFile = "INSERT INTO `sit_seomoreinfo` /r/n" .

"(`id`,`ChannelID`,`CategoryID`,`name`,`url`,`icon`,`type`,`created`,`modified`) /r/n" .

"VALUES /r/n" . implode(",/r/n", $sqlArray).';';

pr($i);

file_put_contents('import_moreinfo.sql',$sqlFile);

?>

  打完收工。

發佈了34 篇原創文章 · 獲贊 6 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章