generate Json through txt (Position) file by php

Asked

Viewed 107 times

0

I’m having a hard time trying to generate the Json using the basis of a txt by certain positions. I could not evolve the code because I do not know how to make a explode in the position I need. Ex:

I have the file test.txt containing the following data:

1001444Denis
1233243Joao
4341233Maria

of position (1) to (4) I have the login

of position (5) to (7) I have the password

of position (8) to (100) I have the name of the person

each line closes exactly at position 100

I did the code below but could not evolve:

<?php
$file = fopen('teste.txt', 'r');
while(!feof($file)){
$content = fgets ($file);
?>

When I give a var_dump it returns me the complete information of each line.

2 answers

1

You can use regex, for example:

<?php
     $subject = "abcdef";
     $pattern = '/^def/';
     preg_match($pattern, substr($subject,3), $matches, PREG_OFFSET_CAPTURE);
     print_r($matches);
?>

Exit:

Array
(
    [0] => Array
        (
            [0] => def
            [1] => 0
        )

)

In your case, you can try to recover the value of each line of the file and separate by regex passing the character classes.

[0-9]{1,4}[0-9]{5,7}[A-z]{8,}

This Pattern would already separate login, password and name.

  • 1

    Jonathan, thank you so much for your help. your method also worked.

1


The function you need is the substr, that returns part of a string.

Then you could do:

<?php
$file = fopen('teste.txt', 'r');
while(!feof($file)){
    $content = fgets ($file);
    $login = substr($content, 0, 4); // Da posição "0" (primeiro caractere), pega 4 caracteres
    $senha = substr($content, 4, 3); // Da posição "4" (quinto caractere), pega 3 caracretes
    $nome = substr($content, 7); // Da posição "7" (oitavo caractere), pega até o fim da linha
}
?>

Reference: http://php.net/manual/en/function.substr.php

  • 1

    Diego, thanks for the help. the code worked really well that way.

Browser other questions tagged

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