如何使一个HTTP请求的形式在网页中的php


How to make an HTTP request to a form in a web page in php

我想实现的是:

我有一个网站,我有完整的源代码访问。在这个网站的页面已创建使用速度模板,我有一个页面与以下形式。

<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完成,那就更好了。任何想法都将受到高度赞赏。

参见:如何使用PHP发布外部表单?

所以,从引用的URL:
<?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
?>