如何在外部网站上提交表单并生成HTML?

问题描述:

我想用PHP创建一个脚本(可能需要JS)将POST数据发送到另一个网页并返回结果。

I would like make a script using PHP (probably need JS) to send POST data to another webpage and get the result back.

例如,域A将有一个带有文本框和提交按钮的表单,域B将有一个脚本,它将填充文本框并按下提交按钮并返回生成的HTML页面。

For example, Domain A will have a form with a textbox and submit button, and Domain B will have a script which will fill the textbox and press the submit button and return the generated HTML page.

以下几行代码可以写在另一个PHP脚本上,

The following lines of code can be written on another php script,

//set POST variables
$url = 'the website from which you need data through post';
$fields = array(
            //post parameters to be sent to the other website
            'text'=>urlencode($_POST['text']), //the post request you send to this  script from your domain.
        );

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

//open connection
$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);

//close connection
curl_close($ch);

现在$ result将包含从其他网站收到的文本。

Now $result will contain the text received from the other website.