PHP Read Text File With Following Labels

194 views Asked by At

So I have these text file which contains some details on it and I would like PHP to extract and distribute each of the data individually.

Example Data on the text file :

Plugin Name: Sample Framework
Description: This is a sample framework
Author: User Friendly

What I wanted is to get each data from the specific labels, like if I want to get the "Plugin Name", so the expected result would be:

Sample Framework

And if I want to get the Description that would be :

This is a sample framework

But I don't know how to do it. The preg_replace or preg_match might work however if there's a rumble data on the text file I don't think that will works but I am open to any answers.

I have also this existing function to determine what kind of details I want to display.

See example below:

<?php
function getDetails($var){
    if($var=='pname'){
        //get the plugin name
    }
} ?>

I think there are many platforms can do that but I can't figure it out.

1

There are 1 answers

1
Rizier123 On BEST ANSWER

This should work for you:

Just read your file into an array with file() and then extract the first row as keys and the other as data, which you then can array_combine() together.

<?php

    $lines = file("test.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $lines = array_map(function($v){
        return explode(":", $v);
    }, $lines);

    $data = array_combine(array_map("array_shift", $lines), array_map("array_pop", $lines));

    print_r($data);

?>

output:

Array
(
    [Plugin Name] =>  Sample Framework
    [Description] =>  This is a sample framework
    [Author] =>  User Friendly
)