PHP Parse file example

→ Are you a new visitor? Please visit the page guidance for new visitors ←

PHP Parse file example

Today I’m going to show you a little example of how you can use PHP to parse a file. Well it really depends on the purpose you’re doing this for, but in all cases basically you need to open the file and read it line by line. There are a few methods that can do this, I have used a few myself. In my last script, I had to create a translation file that uses parts from one file combined with parts from another file. This would be the purpose for this script today.

Why did I had to do this? Well I asked a friend to make a translation for me and due to some misunderstanding the translation was made a little bit wrong, not the translation per se, but rather the format the translation was made was a bit wrong.

For example, lets say we have the following original file:

So this was an original YAML format file and the translation should have been, for instance in German:

however the translation was received with:

So unfortunately the YAML format was now wrong.


So what did I thought? It would have been a fair amount of lines to go over and fix there, where programming can do this so much easier and faster (a few milliseconds!).

So what I did was open the original English file and save the values from the left side of the delimiter “:” in an temporary array and then open the translated file and again save the left or right side in an array (I went with the left side, it doesn’t matter in this case). Of course, when saying open, I mean using php.

Then count both temporary arrays and making sure both have the same number of elements, then parse these temporary arrays and write the final result into a new file.

Here is the code example:

You will see that for lines starting with “#” or blank lines, these will be written from the first array without making any changes to it.

The result would be a new_german.txt file that would contain the proper YAML text format and so could be used as normal:

If you have any comments, please bellow.

Request an article ←