2013-06-20 49 views
0

我試圖實現的是:如何向網頁中的表單發送HTTP請求php

我有一個網站,我有完整的源代碼訪問權限。本網站中的頁面已使用velocity模板創建,並且具有下列格式的頁面。

<h3>form data</h3> 
<form action="$portalPath/test" method="post"> 
    <input type="text" name="text" value="$!self.getTextFromFormData()" /> 
    <input type="submit" /> 
</form> 

現在從另一個用php編寫的應用程序,我想對這個頁面做一個http請求並獲得一個文件下載。 (這是一個html文件)。要做到這一點,我寫了下面的代碼從其他Web應用程序:

$url = 'http://localhost/portal/default/test'; 
$data = array('filename.html'); 

$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); 

但結果顯示我訪問模板(即測試),而不是HTML文件我想下載的HTML源代碼。我想要做的是做一個http請求來自動輸入文件名到表單,並使表單自動提交請求並處理它,並獲得所需的html文件作爲結果。我不知道這是否可能,或者如果可能的話,這是否是正確的方法。如果這可以用curl來完成,那就更好了。任何想法將不勝感激。

+0

一個字捲曲() – 2013-06-20 01:45:14

+0

是否'$ portalPath/test'always導致相同的網址是什麼? –

+0

是的。在後面是python腳本處理提交的數據 – lloydh

回答

1

參見:how can I post an external form using PHP?

所以,從引用網址:

<?php 
    $url = 'http://localhost/portal/default/test'; 
    $fields = array(
    'text'=>urlencode($value_for_field_text), 
); 

    //url-ify the data for the POST 
    foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; } 
    rtrim($fields_string,'&'); 

    // Initialize curl 
    $ch = curl_init(); 

    //set the url, number of POST vars, POST data 
    curl_setopt($ch,CURLOPT_URL,$url); 
    curl_setopt($ch,CURLOPT_POST,count($fields)); 
    curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string); 

    //execute post 
    $result = curl_exec($ch); 

    // Results of post in $result 
?>