本文目錄一覽:
php里如何把 數組裡的指定元素給取出來
一、首先把數組賦予一個變數,如:
$arr=Array(‘0’=’a’,’1’=’b’,’2’=’c’);
二、取出數組的值
取第一個值:$arr[0]
取第二個值:$arr[1]
取第三個值:$arr[2]
取值的方法是通過引用下標號來訪問某個值。
程序代碼如下:
運行結果如下:
擴展資料
設置 PHP 常量
設置常量,使用 define() 函數,函數語法如下:
bool define ( string $name , mixed $value [, bool $case_insensitive = false ] )
該函數有三個參數:
name:必選參數,常量名稱,即標誌符。
value:必選參數,常量的值。
case_insensitive :可選參數,如果設置為 TRUE,該常量則大小寫不敏感。默認是大小寫敏感的。
我們創建一個 區分大小寫的常量,,常量值為 “歡迎訪問”的例子:
?php
// 區分大小寫的常量名
define(“GREETING”, “歡迎訪問”);
echo GREETING; // 輸出 “歡迎訪問”
echo ‘br’;echo greeting; // 輸出 “greeting”
?
參考資料來源:百度百科-php數組
PHP如何從文本中提取指定行數內容
PHP如何從文本中提取指定行數內容?在php中,通過fopen()方法打開文件,在while中使用fgets()方法獲取每行數據,每讀到一行,就使用標識記錄一次,通過累計記錄數計算出文件的行數。下面介紹實現的過程。
方法/步驟分步閱讀
1
/7
新建一個php文件,命名為handle.php,用於講解PHP怎麼獲取文件的行數。
2
/7
新建一個文本文件,命名為test.txt,在裡面輸入四行數據,分別是aaa,bbb,ccc,ddd。
3
/7
在handle.php文件里,使用fopen方法以只讀方式打開test.txt文件,代碼如下:
4
/7
在handle.php文件里,創建一個初始變數i,用於保存文件內容的行數。
5
/7
通過while()語句,使用fgets方法從文件指針中讀取一行,每讀取一行,變數i自加一,直到到達文件末尾停止while的執行。
註:!feof($handle),函數檢測是否已到達文件末尾。
6
/7
最後,使用echo輸出文件的行數,並通過fclose關閉文件資源。代碼如下:
7
/7
在瀏覽器執行handle.php文件,查看輸出的行數,執行的結果為4行。
內容僅供參考並受版權保護
php獲取指定網頁內容
一、用file_get_contents函數,以post方式獲取url
?php
$url= ”;
$data= array(‘foo’= ‘bar’);
$data= http_build_query($data);
$opts= array(
‘http’= array(
‘method’= ‘POST’,
‘header’=”Content-type: application/x-www-form-urlencoded\r\n” .
“Content-Length: ” . strlen($data) . “\r\n”,
‘content’= $data
)
);
$ctx= stream_context_create($opts);
$html= @file_get_contents($url,”,$ctx);
二、用file_get_contents以get方式獲取內容
?php
$url=”;
$html= file_get_contents($url);
echo$html;
?
三、用fopen打開url, 以get方式獲取內容
?php
$fp= fopen($url,’r’);
$header= stream_get_meta_data($fp);//獲取報頭信息
while(!feof($fp)) {
$result.= fgets($fp, 1024);
}
echo”url header: {$header} br”:
echo”url body: $result”;
fclose($fp);
?
四、用fopen打開url, 以post方式獲取內容
?php
$data= array(‘foo2’= ‘bar2′,’foo3’=’bar3’);
$data= http_build_query($data);
$opts= array(
‘http’= array(
‘method’= ‘POST’,
‘header’=”Content-type: application/x-www-form-
urlencoded\r\nCookie:cook1=c3;cook2=c4\r\n” .
“Content-Length: ” . strlen($data) . “\r\n”,
‘content’= $data
)
);
$context= stream_context_create($opts);
$html= fopen(‘;id2=i4′,’rb’,false, $context);
$w=fread($html,1024);
echo$w;
?
五、使用curl庫,使用curl庫之前,可能需要查看一下php.ini是否已經打開了curl擴展
?php
$ch= curl_init();
$timeout= 5;
curl_setopt ($ch, CURLOPT_URL, ”);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents= curl_exec($ch);
curl_close($ch);
echo$file_contents;
?
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/186107.html