How to take data from a form and play in a PHP Array

Asked

Viewed 295 times

1

I have an Android application, which creates a TXT file in PHP, bringing the data from the XML form of Android itself. See the code:

$f = fopen('POST_DATA.txt', 'a');
    fwrite($f, 'ID: '.$id."\r\n");
    $id = uniqid( time() );
    fwrite($f, 'Nome: '.$_POST['nome']."\r\n");
    fwrite($f, 'Cpf: '.$_POST['cpf']."\r\n");
    fwrite($f, 'Bairro: '.$_POST['bairro']."\r\n");
    fwrite($f, 'E-mail: '.$_POST['email']."\r\n");
    fwrite($f, 'Telefone: '.$_POST['telefone']."\r\n\r\n");

    fclose($f);

I would like to play the name data, Cpf, neighborhood, email and phone in an array, which returns the following data, because the query below I can already read it on Android:

$json_str = '{"usuarios": '.'[{"nome":"Felipe", "bairro": São Pedro, "cpf": "11111111", "email" : "[email protected]", "telefone" : "222222222"},'.']}'; 
//faz o parsing da string, criando o array "empregados" 
$jsonObj = json_decode($json_str); $empregados = $jsonObj->empregados; 
    echo $json_str;
  • Why not save the json itself to the txt file? takes some library/function that identa it when saving to txt.

1 answer

1

It would not be easier to already bring this data in json format from your Android app and only read with json_decode?

If not possible, do so with a regex:

$linhas = file('POST_DATA.txt');
$ret = array();
foreach ($linhas as $val) {
    preg_match('/^([\w-]+?): ?(.*)/', $val, $matches);
    if (count($matches) === 0) {
        continue; // linha inválida
    }

     $ret[$matches[1]] = $matches[2];
}
var_dump($ret);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.