将数据发送到站点以获取带有php的Json

时间:2014-10-17 18:03:46

标签: php jquery json

我遇到了问题,问题是我正在使用jquery读取json文件,它运行良好,但现在我必须让它在php中读取它,但问题是我是使用一些数据来获取json的部分:

dataString = "id=" + id + "&todos=" + false;
$.ajax({
type: "POST",
url: "http://www.url.com/example",
data: dataString,
dataType: "json",

success: function( data, textStatus, jqXHR) {

有了这个我没有问题,因为我将数据发送到网站,所以它可以给我我想要的信息,但我不知道如何在PHP中做到这一点,我正在尝试

$str = file_get_contents('http://www.url.com/example.json');
$json = json_decode($str, true); 
var_dump($str);

但当然,由于我没有发送数据,网站没有回复我

我希望有办法。谢谢!

2 个答案:

答案 0 :(得分:1)

如果第一个不存在且无法启用,则应使用curlfsockopen(非常罕见)。

这里是如何使用curl

执行此操作的
<?php
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
    'id' => $id,
    'todos' => false
));
$json = json_decode( curl_exec($ch) );

答案 1 :(得分:0)

乔纳森库恩是对的。

以下是stream_context_create的示例:

<?php

$str = file_get_contents('http://www.url.com/example', false, stream_context_create(
                        array('http' => 
                            array('method' => 'POST',
                                'header' => 'Content-type: application/x-www-form-urlencoded',
                                'content' => 'id=idVal&todos=false'))));
?>