PHP教學 - 利用 curl 抓取網頁資料再存到mysql裡

當我們學會如何抓取網頁的html div 值之後,我就在思考如何將資料存到 mysql 呢?雖然目前用不到,但或許哪天會需要,那麼到底能不能辦到?相信自己,相信 php 沒有辦不到的,我們利用上次抓取台銀美金匯率那個範例來操作一次如下
<html>
<head><meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>抓取美金匯率</title>
<meta http-equiv="refresh" content="300"/>
</head>
<body>
<div style="margin-left:30px">
<?php
$url = "http://rate.bot.com.tw/Pages/Static/UIP003.zh-TW.htm";
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
$content = curl_exec($ch);
curl_close($ch);
preg_match_all('/<td class="decimal">([^<>]+)<\/td>/',$content,$target);
echo "<p>美金部分"."<br>";?>
<table width="100%" border="1">
<tr>
   <td><?php echo "即期匯率買入";?></td>
   <td><?php echo "即期匯率賣出";?></td>
</tr>
<tr>
<?php echo $target[0][2];
      echo $target[0][3];
?>
</tr>
</table></div>
<?php
     echo substr($target[0][2], 20, -5)."</br>";
     echo substr($target[0][3], 20, -5);
?>   
</body></html>
// 這次我利用 substr() 這個函式再次過濾掉我不要的字串果然能成功顯示數字,下面我在寫個php 連 mysql 程式,將資料存到 mysql 中,ok! 果然成功!!
<?php
mysql_connect("localhost", "root", "密碼") or die("無法連結主機");
mysql_select_db("testdb") or die("無法連結資料庫");
mysql_query("SET NAMES utf8");
//$SQL = "INSERT INTO stock VALUES('{$match}')";
$SQL = "INSERT INTO `testdb`.`stock` (`buy_exchange_rate`, `sell_exchange_rate`) VALUES('".substr($target[0][2], 20, -5)."','".substr($target[0][3], 20, -5)."')";
//mysql_query($SQL);
mysql_query($SQL) or die(mysql_error());
?>

留言

張貼留言

這個網誌中的熱門文章

c語言-關於#define用法

PHP教學 - 資料型態(Data Type) - 上

CMD常用網管指令