比較有用的php代碼片斷

來源:互聯網
上載者:User
比較有用的php程式碼片段

一 從網頁中提取關鍵詞

$meta = get_meta_tags('http://www.emoticode.net/');$keywords = $meta['keywords'];// Split keywords$keywords = explode(',', $keywords );// Trim them$keywords = array_map( 'trim', $keywords );// Remove empty values$keywords = array_filter( $keywords );print_r( $keywords );

二 尋找頁面上的所有連結

使用DOM,你可以在任意頁面上抓取連結,樣本如下。
  1. $html = file_get_contents('http://www.example.com');

  2. $dom = new DOMDocument();

  3. @$dom->loadHTML($html);

  4. // grab all the on the page

  5. $xpath = new DOMXPath($dom);

  6. $hrefs = $xpath->evaluate("/html/body//a");

  7. for ($i = 0; $i < $hrefs->length; $i++) {

  8. $href = $hrefs->item($i);

  9. $url = $href->getAttribute('href');

  10. echo $url.'
    ';

  11. }


三 建立資料URI

資料URI可以協助將映像嵌入到HTML/CSS/JS中,從而節省HTTP請求。下面的函數可以利用$file建立資料URI。 function data_uri($file, $mime) {    $contents=file_get_contents($file);    $base64=base64_encode($contents);    echo "data:$mime;base64,$base64";}

四 下載和儲存遠程圖片到你的伺服器

當你在搭建網站時,很可能會從遠程伺服器上下載圖片儲存到你自己的伺服器上,下面的代碼就可以協助你實現這個功能。$image = file_get_contents('http://www.php100.com/image.jpg');file_put_contents('/images/image.jpg', $image);   //Where to save the image

五 移除Microsoft Word HTML標籤

 當你使用Microsoft Word時,會建立很多標籤tag,比如font、span、style、class等,這些標籤在Word中十分有用,但當你從Word中把文本粘貼到網頁上,就會出現很多沒用的標籤。下面實用的函數可以協助你清除所有的Word HTML標籤。function cleanHTML($html) {/// /// Removes all FONT and SPAN tags, and all Class and Style attributes./// Designed to get rid of non-standard Microsoft Word HTML tags./// // start by completely removing all unwanted tags$html = ereg_replace("<(/)?(font|span|del|ins)[^>]*>","",$html);// then run another pass over the html (twice), removing unwanted attributes$html = ereg_replace("<([^>]*)(class|lang|style|size|face)=("[^"]*"|'[^']*'|[^>]+)([^>]*)>","<\1>",$html);$html = ereg_replace("<([^>]*)(class|lang|style|size|face)=("[^"]*"|'[^']*'|[^>]+)([^>]*)>","<\1>",$html);return $html}

六 檢測瀏覽器語言

如果你的網站是多種語言的,下面的代碼可以協助你檢測瀏覽器語言,它會返回用戶端瀏覽器的預設語言。function get_client_language($availableLanguages, $default='en'){    if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {          $langs=explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']);          foreach ($langs as $value){              $choice=substr($value,0,2);              if(in_array($choice, $availableLanguages)){                    return $choice;              }          }      }       return $default;}

七 儲存請求資訊到本地

file_put_contents('/tmp/all.log','mapping'.date("m-d H:i:s")."\n",FILE_APPEND);

八 excel相互轉換日期

//如果去擷取某個excel日期(格式為:2016-03-12),那麼擷取到的是數字,需要經過轉換才能恢複
public function excelTime($date, $time = false) { if(function_exists('GregorianToJD')){ if (is_numeric( $date )) { $jd = GregorianToJD( 1, 1, 1970 ); $gregorian = JDToGregorian( $jd + intval ( $date ) - 25569 ); $date = explode( '/', $gregorian ); $date_str = str_pad( $date [2], 4, '0', STR_PAD_LEFT ) ."-". str_pad( $date [0], 2, '0', STR_PAD_LEFT ) ."-". str_pad( $date [1], 2, '0', STR_PAD_LEFT ) . ($time ? " 00:00:00" : ''); return $date_str; } }else{ // $date=$date>25568? $date+1:25569; /*There was a bug if Converting date before 1-1-1970 (tstamp 0)*/ $ofs=(70 * 365 + 17+2) * 86400; $date = date("Y-m-d",($date * 86400) - $ofs).($time ? " 00:00:00" : ''); return $date; } }

9 json與資料相互轉換

1 json轉換成數組$json = '[{"id":"22","name":"33","descn":"44"}]'; //json格式的數群組轉換成 php的數組$arr = (Array)json_decode($json);echo $arr[0]->id; //用對象的方式訪問(這種是沒有轉換成數組,而是轉換成對象的情況

2 數群組轉換成json$json_arr = array('WebName'=>'11','WebSite'=>'11');$php_json = json_encode($json_arr); //把php數組格式轉換成 json 格式的資料echo $php_json;

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.