Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

skoobi's avatar
Level 13

Post API with csv result

Hi. I've been given an API spec (from external company) which is a POST request and returns a CSV result. Its still being worked on and currently returns as a csv_only like this:

"""
    11111, 2020-07-20 15:44:26, Date Created, System\n
    11111, 2020-07-30 23:29:32, Set Status To Verified Complete, officer1\n
    11111, 2020-08-02 09:16:32, Set Status To Verified Complete, officer2\n
    11111, 2020-08-02 15:07:26, Set Status To Recommended, officer3\n
    11111, 2020-08-02 18:10:47, Set Status To Approved, officer4\n
    11111, 2020-08-02 18:10:51, Approval And Payment Email Sent, officer5\n
    11111, 2020-08-27 11:59:02, Approval And Payment Email Sent, officer6\n
    """

What I'd like to do is to get the csv results and then transform it into JSON or an Array

The structure I'd like to have is :

{
	'id': 11111,
	'timestamp': 2020-07-20 15:44:26,
	'type': 'Date Created',
	'user': 'officer1
},
{
	'id': 11111,
	'timestamp': 2020-07-30 23:29:32,
	'type': 'Set Status To Verified Complete',
	'user': 'officer2
}

I've managed to use Guzzle to get the data, but struggling to format the result. Any help or pointers grateful.

Many thanks

0 likes
4 replies
skoobi's avatar
Level 13

Found a solution. Not sure if theres a better or easier way, but heres what i did:

$lines = explode(PHP_EOL, $result);
$array = array();
foreach ($lines as $key => $value) {
	$array[$key] = str_getcsv($value);
}
skoobi's avatar
Level 13

Next issue or lack of skill possibly. Not worked on the collect() function on Laravel for a while, but, how do i get the results so that the keys are what I want.

array:8 [▼ // app/Http/Controllers/Api/V1/ReportsController.php:45
  0 => array:4 [▼
    0 => "1111"
    1 => "2020-07-20 15:44:26"
    2 => "Date Created"
    3 => "user1"
  ]
  1 => array:4 [▼
    0 => "1111"
    1 => "2020-07-30 23:29:32"
    2 => "Set Status To Verified Complete"
    3 => "user2"
  ]
  2 => array:4 [▼
    0 => "1111"
    1 => "2020-08-02 09:16:32"
    2 => "Set Status To Verified Complete"
    3 => "user3"
  ]
]

How do i go about changing the format from an array to JSON and updating the keys for each so it looks like so?

{
	'id': 11111,
	'timestamp': 2020-07-30 23:29:32,
	'type': 'Set Status To Complete',
	'user': 'officer1
},
{
	'id': 11111,
	'timestamp': 2020-07-30 23:29:32,
	'type': 'Set Status To Complete',
	'user': 'officer2
}
newbie360's avatar
Level 24

@skoobi

$keys = collect(['id', 'timestamp', 'type', 'user']);

$newResult = collect(explode(PHP_EOL, trim($result)))
    ->map(function($line) use ($keys) {
        return $keys->combine(
            array_map('trim', str_getcsv($line))
        )
        ->toJson();
    })
    ->all();

dd($newResult);

Please or to participate in this conversation.