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);
}
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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
$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.