php怎麼擷取檔案裡的內容

來源:互聯網
上載者:User
一個txt檔案,裡面有格式為 ip----網域名稱 的資料,怎麼實現:
xx.com/?ip=xxx.xxx.xxx.xxx,則擷取並顯示對應ip----網域名稱的這個網域名稱,xxx.com
反之,xx.com/?domain=xxx.com,則擷取並顯示對應ip----網域名稱的這個ip,xxx.xxx.xxx.xxx
可以實現嗎?


回複討論(解決方案)

取出檔案的內容,根據換行跟分隔字元切分資料

取出檔案的內容,根據換行跟分隔字元切分資料


具體怎麼實現呢,試寫了下,不過沒用呢

說的稍微詳細點!!!

說的稍微詳細點!!!


一個txt檔案,裡面有格式為 ip----網域名稱 的資料,怎麼實現:
每條資料的ip和網域名稱是對應的
網頁$_GET['ip'],則擷取並顯示對應ip的網域名稱
反之,網頁$_GET['domain'],則擷取並顯示對應網域名稱的ip
如以下資料:
1.2.3.4----abc.com
5.8.6.9----dfg.com
······
網頁get ip,如:?ip=1.2.3.4,則echo對應的網域名稱 abc.com
網頁get domain,如:?domain=dfg.com,則echo對應的ip 5.8.6.9
可以實現嗎?

text.txt

192.168.1.2---xxx.com192.168.1.3---xx.com


test.php
$ip = isset($_GET['ip'])? $_GET['ip'] : '';$domain = isset($_GET['domain'])? $_GET['domain'] : '';if($ip=='' && $domain==''){    exit('ip and domain is empty');}$file = 'test.txt';$filedata = file_get_contents($file);$arr1 = array();$arr2 = array();$data = explode("\n", $filedata);foreach($data as $k=>$v){    $tmp = explode('---', $v);    $arr1[$tmp[0]] = $tmp[1];    $arr2[$tmp[1]] = $tmp[0];}if($ip!=''){    if(isset($arr1[$ip])){        echo $ip.'---'.$arr1[$ip];    }else{        echo 'ip not exists';    }}elseif($domain!=''){    if(isset($arr2[$domain])){        echo $arr2[$domain].'---'.$domain;    }else{        echo 'domain not exists';    }}


http://xxx.com/test.php?ip=192.168.1.2
http://xxx.com/test.php?domain=xxx.com

text.txt

192.168.1.2---xxx.com192.168.1.3---xx.com


test.php
$ip = isset($_GET['ip'])? $_GET['ip'] : '';$domain = isset($_GET['domain'])? $_GET['domain'] : '';if($ip=='' && $domain==''){    exit('ip and domain is empty');}$file = 'test.txt';$filedata = file_get_contents($file);$arr1 = array();$arr2 = array();$data = explode("\n", $filedata);foreach($data as $k=>$v){    $tmp = explode('---', $v);    $arr1[$tmp[0]] = $tmp[1];    $arr2[$tmp[1]] = $tmp[0];}if($ip!=''){    if(isset($arr1[$ip])){        echo $ip.'---'.$arr1[$ip];    }else{        echo 'ip not exists';    }}elseif($domain!=''){    if(isset($arr2[$domain])){        echo $arr2[$domain].'---'.$domain;    }else{        echo 'domain not exists';    }}


http://xxx.com/test.php?ip=192.168.1.2
http://xxx.com/test.php?domain=xxx.com


測試完美運行,非常感謝!
  • 聯繫我們

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