2012年6月22日金曜日

DBから値を取得してFLASH上で利用する方法


20111021.swf

HTMLファイルに値を埋め込み,URL引数渡しする方法では,他ユーザーとリアルタイムに値を共有することができない.
そこで今後は,データベース(以下DB)に全ユーザーの値を集約し,その値をSWFで利用する事とする. 

今回はFlashからDBに直接接続しSQLを発行する方法ではなく,FlashからDBとの仲介役となるPHPファイルに接続し,DBに問い合わせた結果をFlashがXML形式で受け取る方法について説明する.

1.ブラウザを用いて以下の取得先URLにアクセスし,自身のユーザー名/パスワードを用いて値が取得できるか確認.
(取得されるデータはXML形式のため,ページのソースを表示で内容確認)
取得先URL
http://www14026u.sakura.ne.jp/ma/2011/9/status.php?user_name="ユーザー名"&user_pass="パスワード"

2.自身のユーザー名/パスワードを用いて固有の値(ユーザー毎のmoneyとitemの値)を取得できることが確認できたら,現在作成しているFlaファイルに1で取得出来るmoneyの値が反映されるように修正.
Flashの中でユーザー名・パスワードを用いてサーバー上のXMLを取得し,その中に含まれるmoney,kanaの値をステージ上に表示する.

ActionScript(windowレイヤー)
//status_mc.name = _root.name;
//status_mc.money = _root.money;

var db_username = "ユーザー名";
var db_password = "パスワード";
status_xml = new XML();
status_xml.onLoad = userStatus;
status_xml.load("http://www14026u.sakura.ne.jp/ma/2011/9/status.php?user_name='"+db_username+"'&user_pass='"+db_password+"'");
status_xml.ignoreWhite = true;
function userStatus(success) {
 if (success == true) {
  status_mc.money = status_xml.firstChild.firstChild.firstChild.firstChild.nodeValue;
  status_mc.name = status_xml.firstChild.firstChild.firstChild.nextSibling.nextSibling.firstChild.nodeValue;

  //debug
  trace(status_xml.nodeValue);
  trace(status_xml.firstChild.nodeValue);
  trace(status_xml.firstChild.firstChild.nodeValue);
  trace(status_xml.firstChild.firstChild.firstChild.nodeValue);
  trace(status_xml.firstChild.firstChild.firstChild.firstChild.nodeValue);
  trace(status_xml.firstChild.firstChild.firstChild.nextSibling.firstChild.nodeValue);
  trace(status_xml.firstChild.firstChild.firstChild.nextSibling.nextSibling.firstChild.nodeValue);
 }
}

status_mc._visible = false;
window_status = 1;
var key_obj:Object = new Object();
key_obj.onKeyDown = function():Void  {
 var code = Key.getCode();
 if (code == Key.SPACE) {
  if (window_status == 0) {
   status_mc._visible = false;
   window_status = 1;
  } else if (window_status == 1) {
   status_mc._visible = true;
   window_status = 0;
  }
 }
};
Key.addListener(key_obj);


(参考)DBに接続し,ユーザーのstatusを返すPHP
<?php
 $db_user  = "ユーザー名";
 $db_password = "パスワード";
 $db_name = "DB名";
 $db_host  = "接続先サーバ名";

//create xml
    header('Content-type: text/xml; charset=utf-8');
    echo '<?xml version="1.0"?><ma>';

 $user_name = null;
 $user_pass = null;

 if(isset($_GET['user_name'])) {
  $user_name = $_GET['user_name'];
  $user_pass = $_GET['user_pass'];

  $con = mysql_connect($db_host,$db_user,$db_password) or die("error!");
  mysql_select_db($db_name,$con) or die("DB is not exist");
  $strsql = "SET CHARACTER SET UTF8";
  mysql_query($strsql,$con);
  $strsql = "SELECT money, item FROM 2011_users WHERE name = $user_name AND pass = $user_pass;";
  $res = mysql_query($strsql,$con);

  while ($item = mysql_fetch_array($res)) {
   print "<user_status><money>".$item[0]."</money><item>".$item[1]."</item></user_status>";
  }
  mysql_close($con);
}

    echo '</ma>'; 
?>


ダウンロード1

2012年6月21日木曜日

WebAPIの利用(6)

WebAPIの利用(5)に,情報ウインドウ表示機能を追加する.
現状では情報ウインドウに特定の文字列を表示しているのみだが,ユーザーから受け取った場所を示す文字列「$word」を活用して,その場所固有の情報を表示するように各自工夫する事.
例)WebAPIの利用(2)を応用し,その地点の天気,最高/最低気温を表示

map_xmlParse2.php
<?php
$word = htmlspecialchars($_POST['word']);
$sensor = htmlspecialchars($_POST['sensor']);
$url = "http://maps.google.com/maps/api/geocode/xml";
$url .= "?address=".$word."&sensor=".$sensor;
$article = simplexml_load_file($url);

$lat = $article->result->geometry->location->lat;
$lng = $article->result->geometry->location->lng;

print<<<EOF
<html>
 <head>
  <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
  <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
  <title>Google Geocoding and Maps JavaScript API Example</title>
  <link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text
  /css" />
  <script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3.3&sensor=true"></script>
  <script type="text/javascript">
  function initialize() {
   var myLatlng = new google.maps.LatLng($lat, $lng);

   var myOptions = {
    zoom: 15,
    center: myLatlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
   };

   var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

   var marker = new google.maps.Marker({
    position: myLatlng,
    map: map,
    title: '$word'
   });

   var contentStr = 'test';

   var infowindow = new google.maps.InfoWindow({
    content: contentStr,
    size: new google.maps.Size(50, 50)
   });

   google.maps.event.addListener(marker, 'click', function() {
   infowindow.open(map,marker)
   });
  }
  </script>
 </head>
 <body onload="initialize()">
  <div id="map_canvas"></div>
 </body>
</html>
EOF;
?>

情報ウインドウに天気を表示する例
<?php
$word = htmlspecialchars($_POST['word']);
$sensor = htmlspecialchars($_POST['sensor']);
$url = "http://maps.google.com/maps/api/geocode/xml";
$url .= "?address=".$word."&sensor=".$sensor;
$article = simplexml_load_file($url);

$lat = $article->result->geometry->location->lat;
$lng = $article->result->geometry->location->lng;

// get weather
$url2 = "http://www.google.com/ig/api?weather=".$word;
$xml = simplexml_load_file($url2);

$city = $xml->weather->forecast_information->city->attributes();
$forecast_date = $xml->weather->forecast_information->forecast_date->attributes();
$unit_system = $xml->weather->forecast_information->unit_system->attributes();

$current_condition = $xml->weather->current_conditions->condition->attributes();
$temp_c = $xml->weather->current_conditions->temp_c->attributes();
$humidity = $xml->weather->current_conditions->humidity->attributes();
$current_icon = $xml->weather->current_conditions->icon->attributes();
$wind_condition = $xml->weather->current_conditions->wind_condition->attributes();

print<<<EOF
<html>
<head>
 <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
 <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
 <title>Google Geocoding and Maps JavaScript API Example</title>
 <link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text
 /css" />
 <script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3.3&sensor=true"></script>
 <script type="text/javascript">
 function initialize() {
  var myLatlng = new google.maps.LatLng($lat, $lng);

  var myOptions = {
   zoom: 15,
   center: myLatlng,
   mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

  var marker = new google.maps.Marker({
   position: myLatlng,
   map: map,
   title: '$word'
  });

  var contentStr = '$city($forecast_date)[$unit_system]<br />現在の状況:$current_condition<br />気温:$temp_c<br />湿度:$humidity<br /><img src="http://www.google.com$current_icon"><br />風向:$wind_condition';

  var infowindow = new google.maps.InfoWindow({
   content: contentStr,
   size: new google.maps.Size(50, 50)
  });

  google.maps.event.addListener(marker, 'click', function() {
   infowindow.open(map,marker)
  });
 }
 </script>
</head>
<body onload="initialize()">
 <div id="map_canvas"></div>
</body>
</html>
EOF;
?>

WebAPIの利用(5)

WebAPIの利用(4)を更に発展させ,ユーザーが入力した任意の文字列から座標を検索し,地図を表示する.

1.ユーザーが文字列を入力する画面(map_form.html)を用意.
2.画面に配置された送信ボタンを押すことで,postメソッドにより文字列を送信.
3.送信された文字列をphpファイル(map_xmlParse2.php)で受け取り.
4.受け取った文字列を用いて,マッチする座標を検索
5.座標を使って地図を表示.

表示例

LINK

map_form.html
<html>
<head>
 <title>form sample</title>
</head>
<body>
 <form action="map_xmlParse2.php" method="post">
  座標を調べたい文字列 : <input type="text" name="word" />
  <input type="hidden" name="sensor" value="true" />
  <input type="submit" />
 </form>
</body>
</html>

map_xmlParse2.php
<?php
 $word = htmlspecialchars($_POST['word']);
 $sensor = htmlspecialchars($_POST['sensor']);
 $url = "http://maps.google.com/maps/api/geocode/xml";
 $url .= "?address=".$word."&sensor=".$sensor;
 $article = simplexml_load_file($url);

 $lat = $article->result->geometry->location->lat;
 $lng = $article->result->geometry->location->lng;

print<<<EOF
 <html>
 <head>
 <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
 <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
 <title>Google Geocoding and Maps JavaScript API Example</title>
 <link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
 <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
 <script type="text/javascript">
   function initialize() {
     var myLatlng = new google.maps.LatLng(
EOF;
 echo $lat;
 echo ", ";
 echo $lng;
print<<<EOF
     );

     var myOptions = {
       zoom: 15,
       center: myLatlng,
       mapTypeId: google.maps.MapTypeId.ROADMAP
     }
     var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

     var marker = new google.maps.Marker({
       position: myLatlng,
       map: map,
       title:"
EOF;
 echo $word;
print<<<EOF
       "
     });
   }
 </script>
 </head>
 <body onload="initialize()">
   <div id="map_canvas"></div>
 </body>
 </html>
EOF;
?>

Javascriptについて

まずはHello, world.

js_1.html
<html>
 <head>
  <title>Javascript</title>
 </head>
 <body>
  <script type="text/javascript">
   <!--
   document.write("Hello World");
   // -->
  </script>
 </body>
</html>


Javascriptにおける変数の扱いについて.
※Javascriptでは変数を明示的に宣言する場合、var を用います.
※Javascriptでは変数名や関数名などの大文字と小文字は別の文字として扱われます.

js_2.html
<html>
 <head>
  <title>サンプル</title>
 </head>
 <body>
  <script type="text/javascript">
   <!--
   str = "small letter";
   STR = "CAPITAL LETTER";
   document.write(str + STR);
   // -->
  </script>
 </body>
</html>


PHPとJavascriptを組み合わせて利用.
※PHPはサーバーサイドで実行され,Javascriptはクライアントサイドで実行される事に注意.

js_3.php
<?php
$str = "Hello World";

print<<<EOL
<html>
 <head>
  <title>Javascript</title>
 </head>
 <body>
  <script type="text/javascript">
   <!--
   document.write($str);
   // -->
  </script>
 </body>
</html>
EOL;

?>

2012年6月14日木曜日

WebAPIの利用(4)

WebAPIの利用(3)を発展させ,入力した文章中のキーフレーズを画像に置き換えて表示する.
(ユーザーによる)文章入力 →キーフレーズ抽出API →キーフレーズによる画像検索 →元となる文章中のキーフレーズ部分を画像に置換

表示例

LINK

text_form2.html
<html>
 <head>
  <title>text form2</title>
 </head>
 <body>
  <form action="text_xmlParse2.php" method="post">
   変換したい文字列 : <input type="text" name="word" />
  <input type="submit" />
 </form>
 </body>
</html>

text_xmlParse2.php
<?php
$word = htmlspecialchars($_POST['word']);
$appid = "(アプリケーションID)";

$url1 = "http://jlp.yahooapis.jp/KeyphraseService/V1/extract";
$url1 .= "?sentence=".$word."&appid=".$appid;
$article1 = simplexml_load_file($url1);
$keyphrase = $article1->Result->Keyphrase;
$score = $article1->Result->Score;

$url2 = "http://search.yahooapis.jp/ImageSearchService/V2/imageSearch";
$url2 .= "?results=1&query=".$keyphrase."&appid=".$appid;
$article2 = simplexml_load_file($url2);
$image_url = $article2->Result->Url;
$image_thumbnail = $article2->Result->Thumbnail->Url;

print<<<EOF
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>keyphrase replace2</title>
</head>
<body>
EOF;
echo "キーフレーズ:";
echo $keyphrase;

echo "<br />";
echo "スコア:";
echo $score;

echo "<br />";
echo "画像URL:";
echo $image_url;

echo "<br />";
echo "サムネイルURL:";
echo $image_thumbnail;


echo "<br />";
echo "<br />";
echo "元の文章:";
echo $word;

echo "<br />";
echo "<br />";
echo "変換後の文章:";
$temp = str_replace($keyphrase, "<a href=".$image_url."><img src=".$image_thumbnail."></a>", $word);
echo $temp;


print<<<EOF
</body>
</html>
EOF;
?>

WebAPIの利用(3)

Yahoo!のテキスト解析Web APIキーフレーズ抽出を利用して,入力した文章中のキーフレーズを抽出し,そのキーフレーズに対して置換やリンクの付与等を行う.

表示例

LINK

text_form.html
<html>
 <head>
  <title>text form</title>
 </head>
 <body>
  <form action="xmlParse.php" method="post">
   変換したい文字列 : <input type="text" name="word" />
  <input type="submit" />
 </form>
 </body>
</html>

text_xmlParse.php
<?php
$word = htmlspecialchars($_POST['word']);
$appid = "(アプリケーションID)";
$url = "http://jlp.yahooapis.jp/KeyphraseService/V1/extract";
$url .= "?sentence=".$word."&appid=".$appid;
$article = simplexml_load_file($url);

$keyphrase = $article->Result->Keyphrase;
$score = $article->Result->Score;

print<<<EOF
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>keyphrase replace</title>
</head>
<body>
EOF;
echo "キーフレーズ:";
echo $keyphrase;

echo "<br />";
echo "スコア:";
echo $score;

echo "<br />";
echo "元の文章:";
echo $word;

echo "<br />";

echo "<br />";
echo "変換後の文章1:";
$temp1 = str_replace($keyphrase, "<b>禁則事項</b>", $word);
echo $temp1;

echo "<br />";
echo "変換後の文章2:";
$temp2 = str_replace($keyphrase, "<a href=http://www.google.com/search?q=".$keyphrase.">".$keyphrase."</a>", $word);
echo $temp2;

echo "<br />";
echo "変換後の文章3:";
$temp2 = str_replace($keyphrase, "<a href=http://www.google.com/search?tbm=isch&q=".$keyphrase.">".$keyphrase."</a>", $word);
echo $temp2;

print<<<EOF
</body>
</html>
EOF;
?>
※アプリケーションIDの登録はこちら

2012年6月7日木曜日

WebAPIの利用(2)

気象情報(天気予報)APIの利用

表示例

LINK

API URL
http://www.google.com/ig/api?weather=Yokohama,Kanagawa

取得されるXMLのサンプル
<xml_api_reply version="1">
 <weather module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0">
  <forecast_information>
   <city data="Yokohama, Kanagawa Prefecture"/>
   <postal_code data="Yokohama,Kanagawa"/>
   <latitude_e6 data=""/>
   <longitude_e6 data=""/>
   <forecast_date data="2011-11-17"/>
   <current_date_time data="1970-01-01 00:00:00 +0000"/>
   <unit_system data="SI"/>
  </forecast_information>
  <current_conditions>
   <condition data="ところにより曇り"/>
   <temp_f data="63"/>
   <temp_c data="17"/>
   <humidity data="湿度 : 39%"/>
   <icon data="/ig/images/weather/jp_cloudy.gif"/>
   <wind_condition data="風: 南東 4 m/s"/>
  </current_conditions>
  <forecast_conditions>
   <day_of_week data="木"/>
   <low data="11"/>
   <high data="18"/>
   <icon data="/ig/images/weather/jp_sunny.gif"/>
   <condition data="ところにより晴れ"/>
  </forecast_conditions>
  <forecast_conditions>
   <day_of_week data="金"/>
   <low data="10"/>
   <high data="18"/>
   <icon data="/ig/images/weather/jp_cloudy.gif"/>
   <condition data="曇り"/>
   </forecast_conditions>
  <forecast_conditions>
   <day_of_week data="土"/>
   <low data="16"/>
   <high data="21"/>
   <icon data="/ig/images/weather/jp_rainysometimescloudy.gif"/>
   <condition data="雨の可能性"/>
  </forecast_conditions>
  <forecast_conditions>
   <day_of_week data="日"/>
   <low data="14"/>
   <high data="22"/>
   <icon data="/ig/images/weather/jp_rainysometimescloudy.gif"/>
   <condition data="雨の可能性"/>
  </forecast_conditions>
 </weather>
</xml_api_reply>

weather.php
<?php
 $area = "Yokohama";
 $url = "http://www.google.com/ig/api?weather=".$area;

 $xml = simplexml_load_file($url);

//forecast_information
 $city = $xml->weather->forecast_information->city->attributes();
 $forecast_date = $xml->weather->forecast_information->forecast_date->attributes();
 $unit_system = $xml->weather->forecast_information->unit_system->attributes();

//current_conditions
 $current_condition = $xml->weather->current_conditions->condition->attributes();
 $temp_c = $xml->weather->current_conditions->temp_c->attributes();
 $humidity = $xml->weather->current_conditions->humidity->attributes();
 $current_icon = $xml->weather->current_conditions->icon->attributes();
 $wind_condition = $xml->weather->current_conditions->wind_condition->attributes();

//forecast_conditions
 $day_of_week = $xml->weather->forecast_conditions->day_of_week->attributes();
 $low = $xml->weather->forecast_conditions->low->attributes();
 $high = $xml->weather->forecast_conditions->high->attributes();
 $forecast_icon = $xml->weather->forecast_conditions->icon->attributes();
 $forecast_condition = $xml->weather->forecast_conditions->conditionh->attributes();

print<<<EOF
 <html>
 <head>
 <title>google weather sample</title>
 </head>
 <body>
EOF;

 print "場所:".$city."<br />";
 print "予報日:".$forecast_date."<br />";
 print "単位:".$unit_system."<br />";
 print "<br />";
 print "現在の状況<br />";
 print "状況:".$current_condition."<br />";
 print "気温:".$temp_c."<br />";
 print "湿度:".$humidity."<br />";
 print "<img src='http://www.google.com".$current_icon."'><br />";
 print "風向:".$wind_condition."<br />";
 print "<br />";
 print "明日の天気<br />";
 print "曜日:".$day_of_week."<br />";
 print "最低気温:".$low."<br />";
 print "最高気温:".$high."<br />";
 print "<img src='http://www.google.com".$forecast_icon."'><br />";
 print "状況:".$forecast_condition."<br />";

print<<<EOF
 </body>
 </html>
EOF;
?>

WebAPIの利用(1)

twitter public timeline検索APIの利用
表示例

LINK

取得されるXMLのサンプル(一部抜粋)
<?xml version="1.0" encoding="utf-8"?>
<rss>
 <channel>
   <item>
    <title>@Copa3 ありがとうございます。横浜ですかそりゃ、とおくていけませんわ。</title>
    <link>http://twitter.com/sendaimo/statuses/137026307379822592</link>
    <description>@&lt;a class=" " href="http://twitter.com/Copa3"&gt;Copa3&lt;/a&gt; ありがとうございます。&lt;em&gt;横浜&lt;/em&gt;ですかそりゃ、とおくていけませんわ。</description>
    <pubDate>Thu, 17 Nov 2011 04:36:32 +0000</pubDate>
    <guid>http://twitter.com/sendaimo/statuses/137026307379822592</guid>
    <author>sendaimo@twitter.com (Kimiaki Nagase)</author>
    <media:content type="image/jpg" height="48" width="48" url="http://a0.twimg.com/profile_images/825361762/saxbobo02_normal.gif" xmlns:media="http://search.yahoo.com/mrss/" />
    <google:image_link xmlns:google="http://base.google.com/ns/1.0">http://a0.twimg.com/profile_images/825361762/saxbobo02_normal.gif</google:image_link>
    <twitter:metadata xmlns:twitter="http://api.twitter.com/">
     <twitter:result_type>recent</twitter:result_type>
    </twitter:metadata>
   </item>
 </channel>
</rss>

twitter_timeline.php
<?php
 $word = "横浜";
 $url = "http://search.twitter.com/search.rss?q=".$word;

 $rss = simplexml_load_file($url);

 $title = $rss->channel->item->title;
 $link = $rss->channel->item->link;
 $description = $rss->channel->item->description;
 $pubDate = $rss->channel->item->pubDate;
 $author = $rss->channel->item->author;

print<<<EOF
 <html>
 <head>
 <title>twitter sample</title>
 </head>
 <body>
EOF;

 print "title : ".$title."<br />";
 print "link : ".$link."<br />";
 print "description : ".$description."<br />";
 print "pubDate : ".$pubDate."<br />";
 print "author : ".$author."<br />";
 print "image_link : ".$iage_link."<br />";

print<<<EOF
 </body>
 </html>
EOF;
?>