Php 在两个网站之间传递JSON数组
我想在两个网站之间传递一个数组,但我很难做到这一点,在我的localhost中,我尝试以下代码:Php 在两个网站之间传递JSON数组,php,json,curl,Php,Json,Curl,我想在两个网站之间传递一个数组,但我很难做到这一点,在我的localhost中,我尝试以下代码: $array = array("12" => "val", "34" => "val2"); $url = 'http://example1.com/save.php'; $post = 'data='.json_encode($array); $ch = curl_init($url); curl_setopt($ch, CURLOPT_POST, true); curl_
$array = array("12" => "val", "34" => "val2");
$url = 'http://example1.com/save.php';
$post = 'data='.json_encode($array);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_exec($ch);
curl_close($ch);
然后在example1.com/save.php中,我这样做只是为了测试:
$result = json_decode($_POST['data'],true);
foreach ($result as $key => $value) {
echo $key.'='.$value.'<br />';
}
有什么解决方案吗?您应该使用函数检查传递给foreach的是一个数组。错误意味着您正在对非数组的对象执行foreach 查看您的foreach,看看as之前的东西是否实际上是一个数组。不仅在理论上,而且实际上是用来倾倒它的 此外,如果您不确定它是否将是一个数组,您可以始终使用以下PHP示例代码进行检查:
if (is_array($variable)) {
foreach ($variable as $item) {
//do something
}
}
你可能需要改变
$post='data='.json_encode($array)代码>
到
$post='data='.urlencode(json_encode($array))代码>
在任何情况下,只要var\u dump($\u POST)另一侧的code>并查看是否存在编码错误
使用json\u last\u error()
可以检查解码过程中是否有错误。POST['data']
的值是多少?显然出了问题;)在代码中间插入<代码> PrimtTyr($RESULT)<代码>,以确保它实际上是一个关联数组。如果我执行ECH$$POST([数据] ];输出如下:{“1923654\”:“3-0\”,“9874587\”:“0-0\”}@Blazemonger print\u r($result)不显示任何内容。您启用了魔术引号。将您的php更新为不那么愚蠢的旧版本…这就是我得到的:数组(1){[“数据”]=>string(45){\“1923654\”:“3-0\”,“9874587\”:“0-0\”},看起来像是有效的JSON。json_decode
给了你什么?$result=json_decode($_POST['data']);var_dump($结果);输出=空;
if (is_array($variable)) {
foreach ($variable as $item) {
//do something
}
}