1

我有一个标记为 sample.txt 的示例 JSON 数组,它是从捕获用户名和电子邮件的抽奖表单发送的。我正在使用 WooBox,所以 JSON 数组通过每个条目发送信息,所以这里有两个条目:http: //pastebin.ca/3409546

在上一个问题上,有人告诉我打破 ][ 以便 JSON_ENCODE 可以计算出单独的条目。我想只捕获姓名和电子邮件并将数组导入我的电子邮件数据库(活动监视器)。

我的问题是:如何将 JSON 变量标签添加到数组中?如果您看到我的代码,我尝试使用标签 $email。这是正确的形式还是应该是带有 for 循环的 email[0]?

 $url = 'http://www.mywebsite.com/sweeps/test.txt';
 $content = file_get_contents($url);
 $json = json_decode($content,true);

 $tmp = explode('][', $json_string);
 if (!count($tmp)) {
 $json = json_decode($json_string);

 var_dump($json);
 } else {
 foreach ($tmp as $json_part) {
    $json = json_decode('['.rtrim(ltrim($json_string, '['), ']').']');

    var_dump($json);
}
}
 require_once 'csrest_general.php';
 require_once 'csrest_subscribers.php';

 $auth = array(
 'api_key' => 'xxxxxxxxxxxxxxx');
 $wrap = new CS_REST_Subscribers('xxxxxxxxxx', $auth);
 $result = $wrap->add($json(
'EmailAddress' => $email,
'Name' => $custom_3_first,
'Resubscribe' => false
 ));

https://github.com/campaignmonitor/createsend-php/blob/master/samples/subscriber/add.php

4

1 回答 1

1

这应该相当简单:如果你有一个 JSON 字符串并且你调用json_decode($string, true)它,你会在一个 PHP 变量中得到它的等价物,简单明了。从那里,您可以像访问任何 PHP 数组、对象等一样访问它。

问题是,您没有正确的 JSON 字符串。您有一个看起来像 JSON 的字符串,但它不是有效的 JSON。通过linter运行它,你会明白我的意思。

PHP 不知道如何处理您假定的 JSON,因此您必须求助于手动解析,这不是我推荐的路径。不过,你几乎就在那里。

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

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

$url = 'http://www.mywebsite.com/sweeps/test.txt';
$content = file_get_contents($url);    
$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
    ));
}
于 2016-03-23T22:49:50.740 回答