首次寫PHP全程記錄

來源:互聯網
上載者:User

標籤:style   blog   http   color   os   ar   檔案   資料   sp   

    公司用戶端需要一個“氣溫累積”,那麼這個氣溫從哪來呢,經查,我決定用中國氣象網的介面得到。即:1、在伺服器上每天定時或手動讀取中國氣象網的介面得到每個城市的該日json;2、解析並儲存到mysql;3、用戶端訪問mysql得到資料集。

    以上是思路。我決定用一下PHP。

    步驟如下:

一、安裝swampServer

二、建立資料庫:單擊右下角的綠色小表徵圖,開啟其中的phpMyAdmin,我建立了資料庫weather,兩個表citycode和weather,SQL語句如下(初步是這樣,有預留):

CREATE TABLE `citycode` (  `cityname` text NOT NULL,  `citycode` varchar(9) NOT NULL,  `bakup1` int(11) NOT NULL,  `bakup2` int(11) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT=‘城市代碼‘;-- --------------------------------------------------------CREATE TABLE `weather` (  `citycode` varchar(9) NOT NULL,  `date` date NOT NULL,  `high` int(11) NOT NULL,  `low` int(11) NOT NULL,  `weather` text NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;

三、調試好後,在根目錄www下建立檔案index.php,先測試連接資料庫,代碼如下

<?php    echo "嗯";    $con = mysql_connect("localhost", "root", "");    if (!$con)         {            die(‘Could not connecct:‘ . mysql_error());        }    echo "connect successfully!";    mysql_close($con);?>

四、運行了一下,成功,說明mysql連上了。

下面繼續。

五、下面,讀取天氣json,從網上找了一段代碼並執行。index.php內的代碼變為:

 1 <?php 2     echo "嗯"; 3     $con = mysql_connect("localhost", "root", ""); 4     if (!$con)  5         { 6             die(‘Could not connecct:‘ . mysql_error()); 7         } 8     echo "connect successfully!"; 9     mysql_close($con);10     11     $requesturl="http://www.weather.com.cn/data/sk/101010100.html";12     $ch = curl_init();13     // 設定URL和相應的選項14     curl_setopt($ch, CURLOPT_URL, $requesturl);15     curl_setopt($ch, CURLOPT_HEADER, 0);16     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);17     $info=curl_exec($ch);18     // 關閉cURL資源,並且釋放系統資源19     curl_close($ch);20     echo "curl end and then json decode";21     //對返回的json串進行decode,分解後與下面的數組一起合成json串22     $info=json_decode($info,true);23     echo mb_convert_encoding($info[‘weatherinfo‘][‘city‘],‘gb2312‘,‘UTF-8‘);24 ?>

這裡要注意一下,中間出過一個錯誤,要開啟php的curl庫。開啟方法就在右下角綠色表徵圖的php擴充選項裡,勾上php_curl。

下面,我要處理完所有的天氣預報資訊,並儲存到mysql中,同時,要得到所有城市的天氣預報,後續將會把代碼及修改後的mysql資料庫結構發上來,稍等一會。

首次寫PHP全程記錄

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.