G
G
Gloynus Aleos2017-06-23 14:37:46
htaccess
Gloynus Aleos, 2017-06-23 14:37:46

How to convert strings from a TXT file to JSON using PHP with conditions?

There is a .txt file with text inside.

$text_list = file('../templating/a0/update-01.txt');

Each line is a separate object for the future database and, in addition to the content, may have a special difference in the form of a special character at its beginning or several such characters. In my case, it's a tab character.
If there is no tab, then the string is assigned to a property named "title".
If there is a tabulation, then an array is created and the string is added to it.
If there is a tabulation and it is the same as in the previous line, then the line is added to the same array.
If there is a tab and it is more than on the previous line, then another nested array is created and the line is added to it.
There are other conditions, but the main thing for me is to understand how to start the cycle correctly, which will start processing strings according to the conditions and add them to the JSON array. So, I would be happy to receive at least a tip. For due to the lack of this knowledge, I invented my own "bicycle" that does all the necessary processing, but only through the lines from which the array is formed, which are then converted to JSON - long and not competently.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
M
Mr. Joe, 2018-11-23
@Mr_Joe

RewriteRule ^/?news(.*)$ http://www.site.ru/about/news$1 [R=301,L]

A
Alexander, 2017-06-23
@Minifets

You open a file with fopen, and read it line by line with fopen in a loop until you reach the end of the file. In a loop, you write logic that will process the string and add it to json.
php.net/manual/en/function.fread.php

M
MGriboedoff, 2017-06-23
@MGriboedoff

First, decide on the format of your file, it's good that it be XML or something like that.
Compose the structure and possible control characters - the specification.
Then do as Minifest says.
Use regular expressions in the loop body. "PHP preg_match()"
For testing regular expressions, it is convenient to use a service like: https://regex101.com/
Then you can collect the data that you need to collect in an array or even an object.
After parsing is complete, use the "PHP json_encode()" function to convert the object or array to JSON

A
airorfo, 2017-06-30
@airorfo

SW. Gloinus. We understand your concerns. However, it would be very cool if you posted a piece of the "problematic" code and an example of a text file, so that it would be easier for all of us to live.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question