Transform txt to JSON

1

I have a list of cities in a txt file with their respective city name and id, I want to transform it to JSON with a format:

[{"NOMBRE_CIUDAD":"CIUDAD_NOMBRE","ID_CIUDAD":"CIUDAD_ID"}].

What I currently have in the txt is:

"CIUDAD_NOMBRE" "CIUDAD_ID".

Observation: CIUDAD_NOMBRE Y CIUDAD_ID, correspond to some city name and an id.

How could I do this in PHP?

What I have tried is this:

header('Content-Type: application/json');
        $json_data = file_get_contents('listadoComunasMarquee.txt');
        //json_decode($json_data, true);
        echo json_encode($json_data);

But I do not know how to give it the format I require, because it fits like this.

I leave some cities with their respective ID.

OSORNO      104001
COYHAIQUE   114401
PUNTA ARENAS    124901
LAS CONDES  132130
LA PINTANA  132119
RENCA       132108
COLINA      132001
CASTRO      104201
    
asked by Rodrigo 12.12.2017 в 18:08
source

1 answer

1

You almost have it. You only need a couple of intermediate steps:

  • Break the string read by line break ( \n )
  • Each item is broken by a tabulator ( \t )
  • Create an associative array to name each value
  • The code would be like this and it would work:

    <?php
    
    header('Content-Type: application/json');
    $json_data = file_get_contents('listadoComunasMarquee.txt');
    // separamos el fichero en lineas (\n)
    $json_data = preg_split( "/\n/", $json_data );
    // para cada elemento
    for ($x = 0; $x < count($json_data); $x++) {
        // lo separamos por tabulador (\t)
        $dupla = preg_split("/\t/", $json_data[$x], -1, PREG_SPLIT_NO_EMPTY);
        // sustituimos el elemento por un array asociativo similar
        $json_data[$x] = array(
            "NOMBRE_CIUDAD" => $dupla[0],
            "ID_CIUDAD" => $dupla[1]
        );
    }
    echo json_encode($json_data);
    
        
    answered by 12.12.2017 / 18:45
    source