Created
January 4, 2012 15:53
-
-
Save cognitom/1560648 to your computer and use it in GitHub Desktop.
PDFファイルのリンクに容量を記載する
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* PDFファイルのリンクに、容量を記載するためのスクリプト | |
* @author Tsutomu Kawamura <kawamura@cognitom.com> | |
* @copyright Copyright (c) 2012, Tsutomu Kawamura | |
*/ | |
/** | |
* メイン | |
*/ | |
function main(){ | |
//設定 | |
$root_dir = 'path/to/root_dir'; | |
$html_dir = "$root_dir/detail"; | |
$html_files = array('A.html', 'B.html', 'C.html', 'D.html'); | |
$pdf_dir = "$root_dir/pdf"; | |
//処理 | |
$map = getFileSizeList($pdf_dir); | |
foreach ($html_files as $html_file) | |
convertFile("$html_dir/$html_file", $map); | |
} | |
/** | |
* バイト数を読みやすい表記に | |
* @param int $size | |
* @return string | |
*/ | |
function byte2str($size){ | |
$kb = 1024; | |
$mb = 1048576; | |
$gb = 1073741824; | |
$tb = 1099511627776; | |
if(!$size) return '0B'; | |
elseif($size<$kb) return $size.'B'; | |
elseif($size<$mb) return round($size/$kb, 0).'KB'; | |
elseif($size<$gb) return round($size/$mb, 2).'MB'; | |
elseif($size<$tb) return round($size/$gb, 2).'GB'; | |
else return round($size/$tb, 2).'TB'; | |
} | |
/** | |
* 指定ディレクトリ内の各ファイルの容量を調べる | |
* @param string $dir ディレクトリのパス | |
* @return array | |
*/ | |
function getFileSizeList($dir){ | |
$files = array(); | |
foreach (scandir($dir) as $t) | |
if ($t[0] != '.') | |
$files[$t] = byte2str(filesize("$dir/$t")); | |
return $files; | |
} | |
/** | |
* 各HTMLファイル内を置換 | |
* @param string $file ディレクトリのパス | |
*/ | |
function convertFile($file, $map){ | |
$GLOBALS['_temp_callback_data'] = $map;//コールバック関数内で使用するために、一時的にグローバル変数へ。 | |
$html = file_get_contents($file); | |
$html = preg_replace_callback( | |
'|<li><a class="pdf" href="pdf\/([0-9a-z\-]+\.pdf)" title="([^"]+)">([^<]+)<\/a>\(PDF\)<\/li>|', | |
create_function('$matches', | |
'$file = $matches[1];'. | |
'$href = "pdf/$file";'. | |
'$title = $matches[2];'. | |
'$text = $matches[3];'. | |
'$size = $GLOBALS["_temp_callback_data"][$file];'. | |
'return "<li><a class=\\"pdf\\" href=\\"$href\\" title=\\"$title\\">$text</a>(PDF:$size)</li>";' | |
), | |
$html | |
); | |
file_put_contents($file, $html); | |
unset($GLOBALS['_temp_callback_data']);//グローバル変数から削除。 | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
このコードを、次のような感じでTerminalから実行。
php path/to/convert.php
状況に応じて書き換える前提ですが、シェルからPHPを使って、複数ファイルに(比較的)複雑な置換をかける例として。