来自json_decode()的无效数组

时间:2016-03-24 19:18:43

标签: php arrays json

我有一个PHP文件,它抓取.txt文件并解码JSON以将用户的电子邮件和名称输入推送到我的广告系列监控数据库。 JSON是不可靠的,因为新条目添加了][,如下例所示:

[{"email":"drake.scott@test.com","createdate":"2016-03-23 10:44:52","from_email":null,"from_liked_pageid":null,"source":"direct","bonus_entry_url":"\/xxxbyn\/h1lvw5","entry_url":"https:\/\/admin.woobox.com\/manage\/offers\/entries\/20160314-1\/tu%2BcJmnsgyUxE7HM9BCqnRjnza27dGIdr%2BHymHrFmFoprsRgkhZradPrTJ5s18p6ewxYeOOKLpObd%2FWGAS%2BDRw%3D%3D","shareurl":"http:\/\/woobox.com\/qbxbyn\/h1lvw5","picked":"0","actionbutton":"","custom_3_first":"drake","custom_3_last":"scott","custom_4":"4146583264","fullname":"drake scott","id":"vvvbyn"}]
[{"email":"john.roberts@test.com","createdate":"2016-03-23 10:44:52","from_email":null,"from_liked_pageid":null,"source":"direct","bonus_entry_url":"\/xxx\/h1lvw5","entry_url":"https:\/\/admin.woobox.com\/manage\/offers\/entries\/20160314-1\/tu%2BcJmnsgyUxE7HM9BCqnRjnza27dGIdr%2BHymHrFmFoprsRgkhZradPrTJ5s18p6ewxYeOOKLpObd%2FWGAS%2BDRw%3D%3D","shareurl":"http:\/\/woobox.com\/vvvbyn\/h1lvw5","picked":"0","actionbutton":"","custom_3_first":"john","custom_3_last":"adams","custom_4":"4146585018","fullname":"john adams","id":"vvvbyn"}]

我现在遇到的问题是将条目上传到我的数据库。我设法剥离][并执行var_dump($content);显示有效的JSON字符串。但是,执行var_dump($user)会给我0 array(0) { }

这些条目不会上传到我的数据库,因为我的数组中基本上没有任何内容。谁能给我一些关于如何进行的见解?

<?php 

require_once 'csrest_general.php';
require_once 'csrest_subscribers.php';

$auth = array(
'api_key' => 'xxxxxxxxxx');
$wrap = new CS_REST_Subscribers('xxxxxxxxxx', $auth);

$url = 'http://www.mywebsite.com/sweeps/test.txt';
$content = file_get_contents($url);    
$content = str_replace('}][{', '},{', $content);

$tmp = explode('][', $content);
foreach ($tmp as $json_part) {
$user = json_decode('['.rtrim(ltrim($json_string, '['), ']').']', true);
$result = $wrap->add(array(
  'EmailAddress' => $user->email,
  'Name' => $user->fullname,
  'Resubscribe' => true

 ));
}    

if($result->was_successful()) {
echo "Subscribed with code ".$result->http_status_code;

}

else {
 echo "failed";
 var_dump($result->response);
 var_dump($user); 
}
?>

1 个答案:

答案 0 :(得分:1)

文件中连接了多个JSON对象。使JSON有效的最简单方法是创建一个数组:

$content = str_replace('][', ',', $content);
$users   = json_decode($content, true);

然后你有一个多维数组,有多个用户,你需要从中决定你想要什么:

print_r($users);

foreach($users as $user) {
    echo $user['email'] . "\n";
}