私はこの投稿で与えられたサンプル関数を使用しています:
<?php
function do_post_request($url, $data, $optional_headers = null)
{
$params = array('http' => array(
'method' => 'POST',
'content' => $data
));
if ($optional_headers !== null) {
$params['http']['header'] = $optional_headers;
}
$ctx = stream_context_create($params);
$fp = @fopen($url, 'rb', false, $ctx);
if (!$fp) {
throw new Exception("Problem with $url, $php_errormsg");
}
$response = @stream_get_contents($fp);
if ($response === false) {
throw new Exception("Problem reading data from $url, $php_errormsg");
}
return $response;
}
?>
次のように、を使用して同様のアプローチも試しましたfile_get_contents()
。
$options = array(
'http'=>array(
'method'=>"POST",
'header'=>
"Accept-language: en\r\n".
"Content-type: application/x-www-form-urlencoded\r\n",
'content'=>http_build_query(
array(
'arg1'=>'arg_data_1',
'oper'=>'get_data',
'arg2'=>'arg_data_2',
'id_number'=>'7862'
),'','&'
)
));
$context = stream_context_create($options);
$refno = file_get_contents('/path/to/script/script.php',false,$context);
var_dump($refno);
これらの両方のスクリプトで、サーバー スクリプトからの応答は同じで、script.php
. サーバー スクリプトのコードが実行されることはなく、スクリプトのテキスト コンテンツ (PHP コード) は元のスクリプトに戻されます。
すべてのテキストを返すのではなく、特定の部分だけを返すのは少し奇妙です...次のtest.php
ものだけを含むテストスクリプト( )を作成してみました:
<?php
echo '{"a":1,"b":2,"c":3,"d":4,"e":5}';
?>
しかし、それは POST リクエストから何も返さないので、私はそれを含めませんでした. これscript.php
は、多くのロジックを実行し、MySQL クエリを実行してから JSON オブジェクトを返す、より長いスクリプトである必要があります。
望ましい出力は、PHP コードを実行して JSON オブジェクトを返すことです (ajax で動作する方法)。
私は何を間違っていますか?