0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

下層にあるindexファイルからタイトルを抜き出してリスト化する関数

Posted at

はじめに

深夜テンションに身を任せた結果謎のプログラムを錬成してしまったのでアップ。
テストサイトを一々探す手間は省けるかもね。

コード

test.php

function makelinklist(){

// 現在いるディレクトリのパスを取得
$serverroot = (empty($_SERVER["HTTPS"]) ? "http://" : "https://") . $_SERVER["HTTP_HOST"];
$fileroot = dirname(__FILE__);

	// 下層ディレクトリ名をまとめておくリストを宣言
	$dirset = null;

	// 下層ディレクトリを取得する
	if ( $dirs1 = opendir($fileroot) ){
		while ( ($file = readdir($dirs1)) !== false ){
			// ディレクトリ以外のものを排除している
			if( $file != '.' && $file != '..' && $file != '.htaccess' && $file != 'index.php' && $file != 'index.html' ){
				$dirset[] = $file;
			}
		}
	    closedir($dirs1);
	}

	// リンクのリストをつくる
	foreach($dirset as $va){

		echo '<p class="names">'.$va.'</p>';
		echo '<ul>';


		// 取得した下層ディレクトリのリストを利用して、すべてのindexファイルのパスを取得
		$index_pass = glob($fileroot.'/'.$va.'/index.*');

		// indexが存在するディレクトリのみ、さらにindexファイルのタイトルを取得する処理を実行
		if(!empty($index_pass)){
			if ($dirs2 = fopen($fileroot.'/'.$va.'/'.basename($index_pass[0]), 'r')){

				// 前もってaリンクに使うURLをとってくる
				$curpass = $serverroot.'/'.$va.'/'.basename($index_pass[0]);

				// タイトルタグを検索。範囲は~</head>まで
				while (!feof($dirs2)) {
					$ch = null;
					$line = fgets($dirs2);
					// タイトルタグが見つかったなら、そのタイトルを本文としてリンクを作成
					if (preg_match("/<title>(.*?)<\/title>/i", $line, $matches)) {
						echo '<li><a href="'. $curpass . '">' . $matches[1] . '</a></li>';
						$ch = 'a';
						break;
					}
					// タイトルタグが見つからなかった場合、URLの末尾を本文にしてリンクを生成
					if (preg_match("/<\/head>/i", $line)) {
						echo '<li><a href="'. $curpass . '">' . basename($index_pass[0]) . '</a></li>';
						$ch = 'a';
						break;
					}
				}
				// そもそも<head>~</head>自体がindex内に存在しなかった場合、URLの末尾を本文にしてリンクを生成。<head>~</head>が存在していた場合は上記のbreakを通っている=変数$chの中身がaになっているはずなので、この判定を通過することはない
				if($ch === null){
					echo '<li><a href="'. $curpass . '">' . basename($index_pass[0]) . '</a></li>';
				}
				$ch = null;
				fclose($dirs2);
			}
		}
		// indexが存在しない場合、すべてのファイルに対して、URLの末尾を本文にしてリンクを生成
		else{
			$elsegroup = glob($fileroot.'/'.$va.'/*.*');
			foreach($elsegroup as $va2){
				echo '<li><a href="'. $serverroot.'/'.$va.'/'.basename($va2) . '">' . basename($va2) . '</a></li>';
			}
		}
		echo '</ul>';
	}

}

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?