2012年11月25日日曜日

開発環境

『初めてのPHP5』 (David Sklar 著、 桑村 潤 翻訳、 廣川 類 翻訳、 オライリー・ジャパン、2005年、ISBN978-4-87311-257-2)の11章(XML のパースと生成)11.4(演習問題)4を解いてみる。

4.

PHPのコード(TextWrangler)

sample72.php

<?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();
    }
  } 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ニュースフィード(http://news.yahoo.com/rss/)を検索<br />検索用語を入力: ";
    input_text("query", $_POST); 
    input_submit("submit", "search");
    print '<input type="hidden" name="_submit_check" value="1"/>';
    print '</form>';
  }
  function validate_form(){
    $errors = array();
    if(! strlen(trim($_POST['query']))){
      $errors[] = "用語を入力してください";
    }
    return $errors;
  }
  function process_form(){
    $xml = simplexml_load_file('http://news.yahoo.com/rss');
    print "<ul>\n";
    foreach($xml->channel->item as $item){
      if(stristr($item->title, $_POST['query'])){
        print "<li><a href=" . $item->link . ">" . 
          htmlentities($item->title) .
          "</a></li>\n";
      }
    }
    print "</ul>";
  }
?>

HTMLソース

<form method="POST" action="/~kamimura/kamimura_blog/learning_php/sample72.php"/>RSSニュースフィード(http://news.yahoo.com/rss/)を検索<br />検索用語を入力: <input type="text" name="query" value="" /><input type="submit" name="submit" value="search"/><input type="hidden" name="_submit_check" value="1"/></form>

0 コメント:

コメントを投稿