開発環境
- OS X Lion - Apple(OS)
- Apache (Web Server)
- PHP (サーバーサイドプログラミング言語)
- TextWrangler(Text Editor) (BBEditの無料機能制限版、light版)
『初めてのPHP5』 (David Sklar 著、 桑村 潤 翻訳、 廣川 類 翻訳、 オライリー・ジャパン、2005年、ISBN978-4-87311-257-2)の11章(XML のパースと生成)11.4(演習問題)2を解いてみる。
2.
PHPのコード(TextWrangler)
<?php
require 'formhelpers.php';
if(array_key_exists('_submit_check', $_POST)){
if($_POST['_submit_check']){
if($form_errors = validate_form()){
show_form($form_errors);
} else {
process_form();
}
}
} else {
show_form();
}
function show_form($errors = ''){
if($errors){
print "Error:<ul><li>";
print implode("</li><li>", $errors);
print "</li></ul>";
}
print '<form method="POST" action="' . $_SERVER['PHP_SELF'] . '"/>';
print "RSSのアイテムについて入力<br />";
print "<label>タイトル: ";
input_text('title', $_POST);
print "</label><br /><label>リンク: ";
input_text('link', $_POST);
print "</label><br /><label>説明: ";
input_text('description', $_POST);
print "</label><br />";
input_submit("submit", "submit");
print '<input type="hidden" name="_submit_check" value="1" />';
print '</form>';
}
function validate_form(){
$errors = array();
if(! strlen(trim($_POST['title']))){
$errors[] = "タイトルを入力してください";
}
if(! strlen(trim($_POST['link']))){
$errors[] = "リンクを入力してください";
}
if(! strlen(trim($_POST['description']))){
$errors[] = "説明を入力してください";
}
return $errors;
}
function process_form(){
header('Content-Type: text/xml');
print<<<_XML_
<?xml version="1.0" encoding="utf-8" ?>
<rss version="0.91">
<channel>
<title>RSSアイテムのタイトル</title>
<link>リンク</link>
<description>説明</description>
<item>
_XML_;
print '<title>' . htmlentities($_POST['title']) . '</title>';
print '<link>' . htmlentities($_POST['link']) . '</link>';
print '<description>' . htmlentities($_POST['description']) . '</description>';
print "</item></channel></rss>";
}
?>
HTMLソース
<form method="POST" action="/~kamimura/kamimura_blog/learning_php/sample71.php"/>RSSのアイテムについて入力<br /><label>タイトル: <input type="text" name="title" value="" /></label><br /><label>リンク: <input type="text" name="link" value="" /></label><br /><label>説明: <input type="text" name="description" value="" /></label><br /><input type="submit" name="submit" value="submit"/><input type="hidden" name="_submit_check" value="1" /></form>
とりあえず書いたものの、ブラウザによって(というかSafariのみでしか)上手くいかない。。
0 コメント:
コメントを投稿