我会用一个简单的例子来解释:
myphp1.php:
$html = get_html("myphp2.php", "parameter1"); //pseudocode
myphp2.php
<html>
<head>
</head>
<body>
<?php
echo $_POST["parameter1"];
?>
</body>
</html>
所以基本上
$html
将保存 myphp2.php html 输出。我可以这样做吗?
如果你想解释 php 脚本并保存输出,你应该发送一个新的请求。
使用 PHP5,您无需 curl 即可执行此操作:
$url = 'http://www.domain.com/mypage2.php';
$data = array('parameter1' => 'value1', 'parameter2' => 'value2');
$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);
$html = file_get_contents($url, false, $context);
var_dump($html);
使用 file_get_contents 发送 HTTP POST 请求并不难,实际上:如您所猜,您必须使用 $context 参数。
本页的 PHP 手册中给出了一个示例:HTTP 上下文 选项(引用):
详细示例
$url = "http://example.com/submit.php";
$postdata = http_build_query(
array(
'var1' => 'some content',
'var2' => 'doh'
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context);
基本上,您必须使用正确的选项创建一个流(该页面上有完整列表),并将其用作 file_get_contents 的第三个参数——仅此而已 ;-)
作为旁注:一般来说,要发送 HTTP POST 请求,我们倾向于使用 curl,它提供了很多选项——但是流是 PHP 的优点之一,但没有人知道……太糟糕了。 ..