2013-06-20 46 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 
?>