【问题标题】:Multiple records in json and array, and txt reading?json和数组中的多条记录,以及txt读取?
【发布时间】:2018-01-13 18:45:39
【问题描述】:

我正在尝试将以下 Json 发送到我的 api 站点,其中包含一条记录。 它工作正常,但我想发送多个记录,我该怎么做?

稍后我想读取一个 txt 并制作一个包含所有记录的 json。

<?php
//API URL
$url = 'http://mysitexder.net/receiveJson.php';

//create a new cURL resource
$ch = curl_init($url);

//setup request to send json via POST
$data = array(
'cod' => '321',
'name' => 'Jane',
'address' => 'Route 123456'
);
$payload = json_encode(array("user" => $data));

//attach encoded JSON string to the POST fields
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);

//set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));

//return response instead of outputting
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

//execute the POST request
$result = curl_exec($ch);

//close cURL resource
curl_close($ch);

【问题讨论】:

    标签: php arrays json api curl


    【解决方案1】:

    发送一个二维数组:

    $data1 = array(
    'cod' => '321',
    'name' => 'Jane',
    'address' => 'Route 123456'
    );
    $data2 = array(
    'cod' => '555',
    'name' => 'John',
    'address' => '123 Main St'
    );
    $payload = json_encode(array('users' => array($data1, $data2)));
    

    稍后我想读取一个 txt 并制作一个包含所有记录的 json。

    很难说出你的意思。但是您应该以任何您想要的方式解析文本(例如,每一行都是一条记录),从中创建一个 PHP 数组,然后调用 json_encode()

    【讨论】:

    • 太棒了!,是的,我的意思是,txt文件中的每一行都是一条记录,如何解析Txt的行来填充数组,然后对数组进行json_encode?​​span>
    • 如果是 CSV 文件,使用fgetcsv() 将其读入数组,将它们全部收集到另一个数组中,然后使用json_encode() 整个东西。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-16
    • 1970-01-01
    • 1970-01-01
    • 2023-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多