2015-10-05 73 views
0

您知道PHP中有一個名爲file_get_content的方法,它可以獲取所提供url的頁面內容嗎?有沒有相反的方法呢?比如,file_post_content,您可以在其中將數據發佈到外部網站?只是要求教育目的。file_get_content的相反方法

+1

PHP的的file_get_contents功能從本地讀取數據/遠程文件。還有一個名爲file_put_contents(http://php.net/file_put_contents)的函數來在本地寫文件。遠程編寫文件是另一回事。 –

+2

請參閱本問答關於使用'curl'發佈數據http://stackoverflow.com/questions/2138527/php-curl-http-post-sample-code –

+0

我也會迴應cURL。你也可以編寫一個這樣做的函數。 – Twisty

回答

1

您可以使用不捲曲,但file_get_contents PHP這個例子:

$url = 'URL'; 
$data = array('field1' => 'value', 'field2' => 'value'); 
$options = array(
     'http' => array(
     'header' => "Content-type: application/x-www-form-urlencoded\r\n", 
     'method' => 'POST', 
     'content' => http_build_query($data), 
    ) 
); 

$context = stream_context_create($options); 
$result = file_get_contents($url, false, $context); 
var_dump($result); 

查看PHP網站:http://php.net/manual/en/function.file-get-contents.php#102575

0

能寫一個:

<?php 
function file_post_content($url, $data = array()){ 
    // Collect URL. Optional Array of DATA ['name' => 'value'] 
    // Return response from server or FALSE 
    if(empty($url)){ 
     return false; 
    } 

    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL,$url); 
    curl_setopt($ch, CURLOPT_POST, 1); 
    if(count($data)){ 
     curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); 
    } 
    // receive server response ... 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    $svr_out = curl_exec ($ch); 
    curl_close ($ch); 
    return $svr_out; 
} 
?> 
+0

這到底是什麼? – jessica

+0

使用cURL,這將發佈到提供的URL。如果沒有包含數據,它只是做一個POST並返回結果。如果您將數組傳遞給它,這些數據將被髮布到URL中。結果將再次返回。例如,如果你想將一個TimeZone發佈到一個API並取回時間,你可以使用如下的函數:'$ result = file_post_content(「http://api.time.org/」,array('q '=>'UTC'));' – Twisty

+0

如果他們有超過1個字段呢? – jessica