開発環境
- OS X Lion - Apple(OS)
- Apache (Web Server)
- PHP (サーバーサイドプログラミング言語)
- TextWrangler(Text Editor) (BBEditの無料機能制限版、light版)
『初めてのPHP5』 (David Sklar 著、 桑村 潤 翻訳、 廣川 類 翻訳、 オライリー・ジャパン、2005年、ISBN978-4-87311-257-2)の付録 B (正規表現の基本)B.8(演習問題)3を解いてみる。
3.
PHPのコード(TextWrangler)
<html>
<head>
<title>Welcome</title>
<meta charset="utf-8" />
</head>
<body bgcolor="green">
<h1>Hello, Jacob</h1>
<?php
require 'formhelpers.php';
if(array_key_exists('_submit_check', $_POST)){
if($form_errors = validate_form()){
show_form($form_errors);
} else {
process_form();
}
} else {
show_form();
}
function show_form($errors = ''){
print "<h1>1週間の天気予報を取得</h1>";
if($errors){
print 'エラー:<ul><li>';
print implode('</li><li>', $errors);
print '</li></ul>';
}
print '<form method="POST" action="' . $_SERVER['PHP_SELF'] . '" >';
print '<label>zip: ';
input_text('zip', $_POST);
print '</label>';
input_submit('submit', 'submit');
print '<input type="hidden" name="_submit_check" value="1" />';
print '</form>';
}
function validate_form(){
$errors = array();
if(! strlen($_POST['zip'])){
$errors[] = "zipを入力してください。";
} elseif(! preg_match('/^\d{5}$/', $_POST['zip'])){
$errors[] = "郵便番号の形式が違います。";
}
return $errors;
}
function process_form(){
print '<h1>ZIP:' . $_POST['zip'] . ' 7-DAY FORECAST</h1>';
$weather_page = file_get_contents(
'http://www.srh.noaa.gov/zipcity.php?inputstring=' . $_POST['zip']);
$page = strstr($weather_page, '<div class="two-third-first point-forecast-7-day">');
$ul_start = strpos($page, '<ul');
$ul_end = strpos($page, '</ul>') + 5;
if($page){
print substr($page, $ul_start, $ul_end - $ul_start);
} else {
print "<p style='color:red'>取得失敗</p>";
}
print '<a href="' . $_SERVER['PHP_SELF'] . '">zip入力ページに戻る</a>';
}
?>
</body>
</html>
HTMLソース
<html>
<head>
<title>Welcome</title>
<meta charset="utf-8" />
</head>
<body bgcolor="green">
<h1>Hello, Jacob</h1>
<h1>1週間の天気予報を取得</h1><form method="POST" action="/~kamimura/kamimura_blog/learning_php/sample78.php" ><label>zip: <input type="text" name="zip" value="" /></label><input type="submit" name="submit" value="submit"/><input type="hidden" name="_submit_check" value="1" /></form> </body>
</html>
0 コメント:
コメントを投稿