Skip to content

Commit

Permalink
Package launch
Browse files Browse the repository at this point in the history
  • Loading branch information
mtownsend5512 committed Oct 17, 2018
0 parents commit 0f41a39
Show file tree
Hide file tree
Showing 8 changed files with 299 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
composer.lock
vendor
.DS_Store
21 changes: 21 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) Mark Townsend <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
90 changes: 90 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
Easily convert valid xml to a php array.

## Installation

Install via composer:

```
composer require mtownsend/xml-to-array
```

## Quick start

### Using the class

```php
use Mtownsend\XmlToArray\XmlToArray;

$xml = <<<XML
<?xml version="1.0"?>
<request>
<carrier>fedex</carrier>
<id>123</id>
<tracking_number>9205590164917312751089</tracking_number>
</request>
XML;

$array = XmlToArray::convert($xml);

// $array is:
[
'carrier' => 'fedex',
'id' => '123',
'tracking_number' => '9205590164917312751089'
];

```

### Using the global helper

```php
$xml = <<<XML
<?xml version="1.0"?>
<request>
<carrier>fedex</carrier>
<id>123</id>
<tracking_number>9205590164917312751089</tracking_number>
</request>
XML;

$array = xml_to_array($xml);

// $array is:
[
'carrier' => 'fedex',
'id' => '123',
'tracking_number' => '9205590164917312751089'
];
```

## Helpers, methods, and arguments

**Static method**

``XmlToArray::convert($xml, $outputRoot = false)``

The ``$outputRoot`` determines whether or not the php array will have a ``@root`` key. Default is ``false``.

**Helper**

``xml_to_array($xml, $outputRoot = false)``

Arguments are identical to ``XmlToArray::convert`` method.

## Purpose

XML has always been a challenge to work with in PHP compared to other data formats, such as JSON. This package aims to make integrating with XML files or api requests significantly easier. With this package, you might actually like interfacing with XML in your application now.

## Other packages you may be interested in

- [mtownsend/collection-xml](https://github.com/mtownsend5512/collection-xml)

## Credits

- Mark Townsend
- Adrien aka Gaarf
- All Contributors

## License

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.
37 changes: 37 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
{
"name": "mtownsend/xml-to-array",
"description": "Easily convert valid xml to a php array.",
"keywords": [
"laravel",
"xml",
"array",
"convert"
],
"authors": [
{
"name": "Mark Townsend",
"email": "[email protected]",
"role": "Developer"
}
],
"autoload": {
"psr-4": {
"Mtownsend\\XmlToArray\\": "src"
},
"files": [
"src/helpers.php"
]
},
"require": {
"php": "~7.0"
},
"require-dev": {
"phpunit/phpunit": "^6.4"
},
"autoload-dev": {
"psr-4": {
"Mtownsend\\XmlToArray\\Test\\": "tests/"
}
},
"minimum-stability": "stable"
}
22 changes: 22 additions & 0 deletions phpunit.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="vendor/autoload.php"
backupGlobals="false"
backupStaticAttributes="false"
colors="true"
verbose="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false">
<testsuites>
<testsuite name="MyPackage Test Suite">
<directory>tests</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory suffix=".php">src/</directory>
</whitelist>
</filter>
</phpunit>
82 changes: 82 additions & 0 deletions src/XmlToArray.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
<?php

namespace Mtownsend\XmlToArray;

use DOMDocument;

/**
* @author Adrien aka Gaarf & contributors
* @author Mark Townsend
*/
class XmlToArray
{
/**
* Convert valid XML to an array.
*
* @param string $xml
* @param bool $outputRoot
* @return array
*/
public static function convert($xml, $outputRoot = false)
{
$array = self::xmlStringToArray($xml);
if (!$outputRoot && array_key_exists('@root', $array)) {
unset($array['@root']);
}
return $array;
}

protected static function xmlStringToArray($xmlstr)
{
$doc = new DOMDocument();
$doc->loadXML($xmlstr);
$root = $doc->documentElement;
$output = self::domNodeToArray($root);
$output['@root'] = $root->tagName;
return $output;
}

protected static function domNodeToArray($node)
{
$output = [];
switch ($node->nodeType) {
case XML_CDATA_SECTION_NODE:
case XML_TEXT_NODE:
$output = trim($node->textContent);
break;
case XML_ELEMENT_NODE:
for ($i = 0, $m = $node->childNodes->length; $i < $m; $i++) {
$child = $node->childNodes->item($i);
$v = self::domNodeToArray($child);
if (isset($child->tagName)) {
$t = $child->tagName;
if (!isset($output[$t])) {
$output[$t] = [];
}
$output[$t][] = $v;
} elseif ($v || $v === '0') {
$output = (string) $v;
}
}
if ($node->attributes->length && !is_array($output)) { // Has attributes but isn't an array
$output = ['@content' => $output]; // Change output into an array.
}
if (is_array($output)) {
if ($node->attributes->length) {
$a = [];
foreach ($node->attributes as $attrName => $attrNode) {
$a[$attrName] = (string) $attrNode->value;
}
$output['@attributes'] = $a;
}
foreach ($output as $t => $v) {
if (is_array($v) && count($v) == 1 && $t != '@attributes') {
$output[$t] = $v[0];
}
}
}
break;
}
return $output;
}
}
15 changes: 15 additions & 0 deletions src/helpers.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

if (!function_exists('xml_to_array')) {
/**
* Convert valid XML to an array.
*
* @param string $xml
* @param bool $outputRoot
* @return array
*/
function xml_to_array($xml, $outputRoot = false)
{
return \Mtownsend\XmlToArray\XmlToArray::convert($xml, $outputRoot);
}
}
29 changes: 29 additions & 0 deletions tests/CollectionXmlTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

use PHPUnit\Framework\TestCase;

class CollectionXml extends TestCase
{

/** @test array */
protected $testArray = [];

/** @test string */
protected $testXml;

public function setUp()
{
$this->testArray = [
'carrier' => 'fedex',
'id' => 123,
'tracking_number' => '9205590164917312751089',
];
$this->testXml = '<?xml version="1.0"?><root><carrier>fedex</carrier><id>123</id><tracking_number>9205590164917312751089</tracking_number></root>';
}

/** @test */
public function xml_can_convert_to_array()
{
$this->assertEquals(xml_to_array($this->testXml), $this->testArray);
}
}

0 comments on commit 0f41a39

Please sign in to comment.