dExIT
dExIT

Reputation: 222

How to parse Comma delimited string with newline to JSON in PHP to use with Morris.JS

I send SOAP API requests to a Service, but the response comes in one field and consists of a string :

$string = '"users","actions","movements" "user1","111","54" "user2","87","123" "user3","92","23"'

when i do:

$json = json_encode($string);

does not result in valid JSON.

I've tried :

$Data = str_getcsv($incomingdata, "," , '"' , "\n"); 
$json2 = json_encode($Data);

It is not parsed correctly to use with MORRIS.JS and results in complete rubbish

The "users","actions","movements" are the headers. Could someone point me in the right direction please ?

The needed result should look like this:

[0] => Array
        (
            [user] => user1
            [actions] => 630
            [movements] => 87
        )
[1] => Array
        (
            [user] => user2
            [actions] => 330
            [movements] => 187
        )

and so on

Upvotes: 0

Views: 2255

Answers (3)

dExIT
dExIT

Reputation: 222

I finally made it happen this way:

<?php
include("functions.php");

$data = MYFunction('Template','FilterBy','SortBy','Colums'); //here DATA FROM SOAP
//............
//............
$data = $pickrate;
file_put_contents('file.csv', $pickrate); // placing acquired data to CSV
$csv= file_get_contents('file.csv'); //open saved csv file
$array = array_map("str_getcsv", explode("\n", $csv)); //create array map and explode on \n

if (($handle = fopen('file.csv', 'r')) === false) {
    die('Error opening file'); // no access error handling
}

$headers = fgetcsv($handle, 1024, ','); //generate headers from first row delim, by ","
$complete = array(); //opening array

while ($row = fgetcsv($handle, 1024, ',')) { //read each row delim by ","
    $complete[] = array_combine($headers, $row); // push it into var $complete and combine $headers row with $row
}

fclose($handle); // closes the array gen

//include this file and then call <? echo json_encode($complete); ?> in Morris.js DATA field
?>

Upvotes: 0

capcj
capcj

Reputation: 1535

You need to convert your string to an array before encode with JSON, try to use explode instead:

$result = explode(',', $string);
$json = json_encode($result);

If you don't want to ignore new lines:

$result = explode(' ', $string);
$i = 0;
foreach ($result as $item){
  $resultJ[$i] = explode(',', $item);
  $i++;
}
$json = json_encode($resultJ);

To remove the slashes and \n's in your json: You can use str_replace in the json:

str_replace(array("\\", "\n"), "", $json);

or in the $string (recommended), because yours \ is an natural escaping to " by json encoding:

str_replace('"', "", $string);

QUESTION UPDATED, ANSWER TOO:

    <?php
$string = str_replace('"', "", '"users","actions","movements" "user1","111","54" "user2","87","123" "user3","92","23"');
$result = explode(' ', $string);
$result2 = array();
$i = 0;
//Load the arrays
foreach ($result as $item) {
  $result2Array[$i] = explode(',', $item);
  $i++;
}
$total = count($result2Array) - 1;
for ($i = 1; $i <= $total; $i++) {
  $j = 0;
  //Bring values to each index
  foreach ($result2Array[0] as $index){
    $resultF[$i-1][$index] = $result2Array[$i][$j];
    $j++;
  }
}


var_dump($resultF);
$json = json_encode($resultF);

Upvotes: 0

Danijel
Danijel

Reputation: 12709

You shoud put the example of json expected, in any case, maybe this helps you:

$string = '"users","actions","movements"
"user1","111","54"
"user2","87","123"
"user3","92","23"';

// in case of csv where rows are delimited with new lines use explode( "\n", $string )
// if is delimited with space character use explode( ' ', $string )
$array = array_map( 'str_getcsv', explode( "\n", $string ) );
array_shift( $array );

array_walk( $array, function( &$v, $k, $keys ) {
    $v = array_combine( $keys, $v );
}, [ 'user', 'actions', 'movements' ] );


print_r( $array );
/*
Array
(
    [0] => Array
        (
            [user] => user1
            [actions] => 111
            [movements] => 54
        )

    [1] => Array
        (
            [user] => user2
            [actions] => 87
            [movements] => 123
        )

    ...
)
*/

print_r( json_encode( $array ) );
/* 
[
    {"user":"user1","actions":"111","movements":"54"},
    {"user":"user2","actions":"87","movements":"123"},
    {"user":"user3","actions":"92","movements":"23"}
]
*/

Upvotes: 1

Related Questions