PHPackages                             artkoder/kvpparser - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Parsing &amp; Serialization](/categories/parsing)
4. /
5. artkoder/kvpparser

ActiveLibrary[Parsing &amp; Serialization](/categories/parsing)

artkoder/kvpparser
==================

A library to read and parse files with key value pairs.

v0.1.5(2y ago)0271MITPHP

Since Sep 23Pushed 2mo ago1 watchersCompare

[ Source](https://github.com/musciencia/kvpparser)[ Packagist](https://packagist.org/packages/artkoder/kvpparser)[ RSS](/packages/artkoder-kvpparser/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (1)Versions (7)Used By (1)

KVP Parser
==========

[](#kvp-parser)

A library to read and parse files with key value pairs.

What is a KVP file
------------------

[](#what-is-a-kvp-file)

A KVP file consists of records of key value pairs separated by empty lines.

Here is an example:

```
date: 2023-01-01
description: Electric company example Inc.
category: Electricity
amount: 120

date: 2023-02-01
description: Real estate example Inc.
category: Rent
amount: 1500

```

Here is a differnt example with a comment. Lines starting with `#` are comments ignored by the parser.

```
# Budget report routes
name: budget-report
path: /budget/{start}/{end}
method: get
controller: ArtKoder\Peasy\Controllers\Budget::report

name: budget-index
path: /budget
method: get
controller: ArtKoder\Peasy\Controllers\Budget::index

```

I started using this type of file in different projects because it's similar to yaml but without the nesting and it's parsing complexity. So I decided to build a library to make the code reusable.

Installation
------------

[](#installation)

### Using composer

[](#using-composer)

```
composer require artkoder/kvpparser
```

How to use this library
-----------------------

[](#how-to-use-this-library)

Here are some examples:

### Parse a single file

[](#parse-a-single-file)

Supose we have the following file named `budget.kvp`:

```
date: 2023-01-01
description: some description
category: some category
amount: 1000

date: 2023-01-02
description: another description
category: another category
amount: 2000

date: 2023-01-03
description: one more description
category: one more category
amount: 3000

```

We can parse the file and receive an associative array by running the following code:

```
$data = KvpParser::parseFile(__DIR__ . '/../data/budget.kvp');
print_r($data);
```

Here is the output:

```
Array
(
    [0] => Array
        (
            [date] => 2023-01-01
            [description] => some description
            [category] => some category
            [amount] => 1000
        )

    [1] => Array
        (
            [date] => 2023-01-02
            [description] => another description
            [category] => another category
            [amount] => 2000
        )

    [2] => Array
        (
            [date] => 2023-01-03
            [description] => one more description
            [category] => one more category
            [amount] => 3000
        )

)
```

### Parse multiple files inside a directory recursively

[](#parse-multiple-files-inside-a-directory-recursively)

You can specify a directory. KvpParser will parse all the files found in that directory and subdirectories.

```
$directory = '/path/to/your/data';
$data = KvpParser::parseRecursive($directory);
```

By default KvpParser will look for files with extension `.kvp`. But you can specify any file extensions. For example:

```
$directory = '/path/to/your/data';
$includExtension = ['kvp', 'dat'];
$data = KvpParser::parseRecursive($directory, $includeExtensions);
```

### Convert a CSV file to a KVP file

[](#convert-a-csv-file-to-a-kvp-file)

This is very convenient. Suppose that you have a csv file with the following data from your bank statement:

```
"Account Type","Account Number","Transaction Date","Cheque Number","Description 1","Description 2","CAD$","USD$"
Chequing,123-4567,6/12/2023,,"C - IDP REFUND-0819","COSTCO WHOLESAL ",183.95,
Chequing,123-4567,6/12/2023,,"COSTCO WHOLESAL","IDP PURCHASE - 0746 ",-276.94,
Chequing,123-4567,6/13/2023,,"AUTOMOBILE RENT","TOYOTA FINANCE ",-129.12,
```

Let's say that we are only interested in the following data: Date, Description 1 and CAD$. But we also want to change the column names in our resultin `.kdp` file.

Here is what we can do:

```
$csvFile = __DIR__ . '/../data/transactions.csv';
$kdpFile = __DIR__ . '/../data/transactions.kdp';
$columnMap = [
    "Date" => "Transaction Date",
    "Description" => "Description 1",
    "Amount" => "CAD$"
];
KvpParser::csvToKvp($csvFile, $kdpFile, $columnMap);
```

Here are the contents of `transactions.kdp`:

```
Date: 6/12/2023
Description: C - IDP REFUND-0819
Amount: 183.95

Date: 6/12/2023
Description: COSTCO WHOLESAL
Amount: -276.94

Date: 6/13/2023
Description: AUTOMOBILE RENT
Amount: -129.12

```

If no `$columnMap` is specified, the column names in the `csv` file will become the name of the properties in the `kvp` file.

Some times you need to do some processing of data during mapping, we can do that adding closures to the map array.

In our previous example, suppose you want ot combine both description columns and format date to be `Y-m-d`.

Here is how you would do it:

```
function formatDate($data) {
    $inputDate = $data['Transaction Date'];
    $inputFormat = 'm/d/Y';
    $outputFormat = 'Y-m-d';
    // Create a DateTime object from the input date with the specified format
    $dateTime = DateTime::createFromFormat($inputFormat, $inputDate);

    // Check for errors in parsing the date
    if ($dateTime === false) {
        return false; // Return false if the parsing fails
    }

    // Format the DateTime object in the desired output format
    $formattedDate = $dateTime->format($outputFormat);

    return $formattedDate;
}

$columnMap = [
    "Date" => 'formatDate',
    "Account" => "Account Number",
    "Description" => function($data) {
        return $data['Description 1'] . " - " . $data['Description 2'];
    },
    "Amount" => "CAD$",
    "Category" => "uncategorized"
    ];

KvpParser::csvToKvp($csvFile, $kdpFile, $columnMap);
```

Notice also that the column `uncategorized` does not exist. In this case the word `uncategorized` would be use as the value.

###  Health Score

28

—

LowBetter than 54% of packages

Maintenance55

Moderate activity, may be stable

Popularity7

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity37

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~1 days

Total

6

Last Release

964d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/b6e20f24bcfdd5aa67d57d8d8bbc698eb9408dd3812d951f842898a62026c0e4?d=identicon)[musciencia](/maintainers/musciencia)

---

Top Contributors

[![musciencia](https://avatars.githubusercontent.com/u/28911391?v=4)](https://github.com/musciencia "musciencia (12 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/artkoder-kvpparser/health.svg)

```
[![Health](https://phpackages.com/badges/artkoder-kvpparser/health.svg)](https://phpackages.com/packages/artkoder-kvpparser)
```

###  Alternatives

[mtdowling/jmespath.php

Declaratively specify how to extract elements from a JSON document

2.0k472.8M135](/packages/mtdowling-jmespathphp)[opis/closure

A library that can be used to serialize closures (anonymous functions) and arbitrary data.

2.6k230.0M284](/packages/opis-closure)[masterminds/html5

An HTML5 parser and serializer.

1.8k242.8M229](/packages/masterminds-html5)[sabberworm/php-css-parser

Parser for CSS Files written in PHP

1.8k191.2M65](/packages/sabberworm-php-css-parser)[michelf/php-markdown

PHP Markdown

3.5k52.4M345](/packages/michelf-php-markdown)[jms/metadata

Class/method/property metadata management in PHP

1.8k152.8M88](/packages/jms-metadata)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
