GithubHelp home page GithubHelp logo

parser's Introduction

Parser

Latest Version on Packagist Software License Build Status Total Downloads

Simple PHP Parser Library for API Development, parse a post http payload into a php array.

Also see the Responder library for handling output.

Installation

Begin by installing this package through Composer. From the Terminal:

composer require nathanmac/parser

Laravel/Lumen Users

Laravel/Lumen Verison Supported Library Verison
Laravel/Lumen 5+ > 3.*
Laravel 4 2.*

Laravel Users (Adding the Service Provider)

If you are a Laravel user, then there is a service provider that you can make use of to automatically prepare the bindings and such.

Include the service provider within app/config/app.php.

'providers' => [
    ...,
    Nathanmac\Utilities\Parser\ParserServiceProvider::class
];

And, for convenience, add a facade alias to this same file at the bottom:

'aliases' => [
    ...,
    'Parser' => Nathanmac\Utilities\Parser\Facades\Parser::class,
];

Lumen Users (Adding the Service Provider)

If you are a Lumen user, then there is a service provider that you can make use of to automatically prepare the binding and such.

// bootstrap/app.php

$app->register('Nathanmac\Utilities\Parser\ParserServiceProvider');

Lumen users can also add the facade alias.

// bootstrap/app.php

class_alias('Nathanmac\Utilities\Parser\Facades\Parser', 'Parser');

Using the Facade

public function index()
{
    Parser::payload('application/json');

    Parser::json($payload);		    // JSON > Array
    Parser::xml($payload);		    // XML > Array
    Parser::yaml($payload);		    // YAML > Array
    Parser::querystr($payload);	    // Query String > Array
    Parser::serialize($payload);	// Serialized Object > Array
	Parser::bson($payload);	        // BSON > Array
	Parser::msgpack($payload);	    // MSGPack > Array

    Parser::all();                         // Return all values
    Parser::has('key');                    // Does a key exist, with value.
    Parser::get('key', 'default value');   // Get value by key, set an optional default.
    Parser::only('id', 'name', 'email');   // Only return value from the selected keys.
    Parser::except('password');            // Don't return values from the selected keys.
    Parser::mask($mask);                   // Return masked values (see Mask Function, below).
}

All the examples below assume you aren't using Laravel (or Lumen), and therefore don't have access to the facade. As with any other facade, instead of:

$parser = new Parser();

$parser->{$method}($payload);

just use:

Parser::{$method}($payload);

Usage

Parsing Functions

$parser->json($payload);		// JSON > Array
$parser->xml($payload);		    // XML > Array
$parser->yaml($payload);		// YAML > Array
$parser->querystr($payload);	// Query String > Array
$parser->serialize($payload);	// Serialized Object > Array
$parser->bson($payload);     	// BSON > Array
$parser->msgpack($payload);   	// MSGPack > Array

Parse Input/Payload (PUT/POST)

$parser = new Parser();
$parser->payload();		                // Auto Detect Type - 'Content Type' HTTP Header
$parser->payload('application/json');	// Specifiy the content type

Helper functions

$parser = new Parser();
$parser->all();                         // Return all values
$parser->has('key');                    // Does a key exist, with value.
$parser->get('key', 'default value');   // Get value by key, set an optional default.
$parser->only('id', 'name', 'email');   // Only return value from the selected keys.
$parser->except('password');            // Don't return values from the selected keys.
$parser->mask($mask);                   // Return masked values (see Mask Function, below).

Mask function

The mask function processes payload data using a configuration mask, thereby returning only a selected subset of the data. It works just like the only method but with the added benefit of allowing you to specify a mask in the form of an array, this means you can generate masks on-the-fly based on system and/or user defined conditions.

Demo
Mask

Defining the mask, masks consist of basic array structure, for this particular example we have some rules for the data to be returned they include: - the title of the post - all the body's for all the comments.

$mask = [
    'post' => [
        'title' => '*',
        'comments' => [
            'body' => '*'
        ]
    ]
];
Sample Payload
{
    "post": {
        "title": "Hello World",
        "author": "John Smith",
        "comments": [
            {"body": "This is a comment", "date": "2015-02-20"},
            {"body": "This is another comment", "date": "2015-05-09"}
        ]
    }
}
Applying the Mask
    $parser = new Parser();
    $output = $parser->mask($mask);
Output

This is the output generated as a result of applying the mask against the sample payload provided above.

$output = [
    'post' => [
        'title' => 'Hello World',
        'comments' => [
            ['body' => 'This is a comment'],
            ['body' => 'This is another comment']
        ]
    ]
];

Wildcards/Special Keys (*, %, :first, :last, :index[0], :item[0])

$parser = new Parser();
$parser->has('message.*');          // Does a key exist, with value. (Wildcard key returns first item found)
$parser->get('message.*');          // Get value by key. (Wildcard key returns first item found)
$parser->has('message.:first');     // Does a key exist, with value. (:first key returns first item found)
$parser->get('message.:first');     // Get value by key. (:first key returns first item found)
$parser->has('message.:last');      // Does a key exist, with value. (:last key returns last item found)
$parser->get('message.:last');      // Get value by key. (:last key returns last item found)
$parser->has('message.:index[0]');  // Does a key exist, with value. (:index[0] key returns item at index 0)
$parser->get('message.:index[0]');  // Get value by key. (:index[0] key returns item at index 0)
$parser->has('message.:item[0]');   // Does a key exist, with value. (:item[0] key returns item at index 0)
$parser->get('message.:item[0]');   // Get value by key. (:item[0] key returns item at index 0)

Parse JSON

$parser = new Parser();
$parsed = $parser->json('
	{
		"message": {
			"to": "Jack Smith",
			"from": "Jane Doe",
			"subject": "Hello World",
			"body": "Hello, whats going on..."
		}
	}');

Parse XML

$parser = new Parser();
$parsed = $parser->xml('
			<?xml version="1.0" encoding="UTF-8"?>
			<xml xmlns:ns="http://example.com/xmlns">
				<message status="sent">
					<ns:meta hint="created">Created 5 minutes ago</ns:meta>
					<to>Jack Smith</to>
					<from>Jane Doe</from>
					<subject>Hello World</subject>
					<body>Hello, whats going on...</body>
				</message>
			</xml>');

Parse Query String

$parser = new Parser();
$parsed = $parser->querystr('to=Jack Smith&from=Jane Doe&subject=Hello World&body=Hello, whats going on...');

Parse Serialized Object

$parser = new Parser();
$parsed = $parser->serialize('a:1:{s:7:"message";a:4:{s:2:"to";s:10:"Jack Smith";s:4:"from";s:8:"Jane Doe";s:7:"subject";s:11:"Hello World";s:4:"body";s:24:"Hello, whats going on...";}}');

Parse YAML

$parser = new Parser();
$parsed = $parser->yaml('
				---
				message:
				    to: "Jack Smith"
				    from: "Jane Doe"
				    subject: "Hello World"
				    body: "Hello, whats going on..."
				');

Parse BSON

$parser = new Parser();
$parsed = $parser->bson('BSON DATA HERE');

Parse MSGPack

$parser = new Parser();
$parsed = $parser->msgpack('MSGPACK DATA HERE');

Custom Parsers/Formatters

You can make your own custom parsers/formatters by implementing FormatInterface, the below example demostrates the use of a custom parser/formatter.

use Nathanmac\Utilities\Parser\Formats\FormatInterface;

/**
 * Custom Formatter
 */

class CustomFormatter implements FormatInterface {
    /**
     * Parse Payload Data
     *
     * @param string $payload
     *
     * @return array
     *
     * @throws ParserException
     */
    public function parse($payload)
    {
        $payload; // Raw payload data

        $output = // Process raw payload data to array

        return $output; // return array parsed data
    }
}

Using the CustomFormatter

use Acme\Formatters\CustomFormatter;

$parser = new Parser();
$parsed = $parser->parse('RAW PAYLOAD DATA', new CustomFormatter());

Autodetecting the CustomFormatter

use Acme\Formatters\CustomFormatter;

$parser = new Parser();
$parser->registerFormat('application/x-custom-format', 'Acme\Formatters\CustomFormatter');
$parser->payload('application/x-custom-format');

Testing

To test the library itself, run the tests:

composer test

Contributing

Please see CONTRIBUTING for details.

Credits

License

The MIT License (MIT). Please see License File for more information.

Appendix

Supported Content-Types
XML
---
application/xml > XML
text/xml > XML

JSON
----
application/json > JSON
application/x-javascript > JSON
text/javascript > JSON
text/x-javascript > JSON
text/x-json > JSON

YAML
----
text/yaml > YAML
text/x-yaml > YAML
application/yaml > YAML
application/x-yaml > YAML

BSON
----
application/bson > BSON

MSGPack
-------
application/msgpack > MSGPack
application/x-msgpack > MSGPack

MISC
----
application/vnd.php.serialized > Serialized Object
application/x-www-form-urlencoded' > Query String

parser's People

Contributors

aroy314 avatar artn avatar danhunsaker avatar djereg avatar flofloflo avatar matriphe avatar mubinov avatar nathanmac avatar nekosaur avatar scottpnelson avatar teimos avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

parser's Issues

Documentation isn't clear.

Thanks for this package..
I'm trying to get Lumen to convert my default DB::all() to a XML that I can define the tree.

This is for google product services that requires a XML feed, do you know if this package can allow me to complete that task?

I've tried doing something like..

$payload = Product::findOrFail($id);

        return Parser::xml($payload);

But I get Failed To Parse XML

Weird behaviour

Hello,
I've been playing around with this package but can't make it behave the way I'm expecting to.
I'm using Laravel 5.4 and PHP 7.1 (this setup could be the reason of my problem...). I'm using the very simple code example :

Parser::json('{
            "post": {
                "title": "Hello World",
                "author": "John Smith",
                "comments": [
                    {"body": "This is a comment", "date": "2015-02-20"},
                    {"body": "This is another comment", "date": "2015-05-09"}
                ]
            }
        }');
dd(Parser::has('post.title'));

This returns false....

$parser = new \Nathanmac\Utilities\Parser\Parser();
    $parser->json('{
            "post": {
                "title": "Hello World",
                "author": "John Smith",
                "comments": [
                    {"body": "This is a comment", "date": "2015-02-20"},
                    {"body": "This is another comment", "date": "2015-05-09"}
                ]
            }
        }');
dd($parser->has('post.title'));

False again...

$parser = new \Nathanmac\Utilities\Parser\Parser();
    $parsed = $parser->json('{
            "post": {
                "title": "Hello World",
                "author": "John Smith",
                "comments": [
                    {"body": "This is a comment", "date": "2015-02-20"},
                    {"body": "This is another comment", "date": "2015-05-09"}
                ]
            }
        }');
dd($parsed);

Here the output is what I'm expecting. Tried ->all(), ->get(), ... Even tried mask but the output is always empty.

I'm confused. Any idea ?

Thanks,

Xavier

XML Parsing and attributes

When using the XML parser, it does not take into account any attributes that might have been defined for an element.

Example:

<?xml version="1.0" encoding="UTF-8"?>
<books>
  <book>
    <title>Example</title>
    <author>Author</author>
    <price currency="EUR">25.50</price>
  </book>
</books>

The price attribute currency is nowhere to be found in the resulting PHP array.

Has there been any discussion on how to tackle this issue? That is a pretty important part of XML parsing, to be able to get the attributes of elements.

Thanks!

laravel/framework v5.4.36

Have you the right version for install in laravel/framework v5.4.36 ??? i tried every version without success.

Lumen json

Yaml output to json. I think that is worng for this package

Lumen Port ?

Are you planning to port this to Lumen ? or is there any way i can make this work with Lumen as it is ?
Thank you for this great package :)

How do I filter the result of the parser?

I'm writing an API that calls an external API. The external API returns data as XML, and my API needs to return data as JSON. I have the following code that works fine

$client = new Client(['base_uri' => $this->baseUri]);
$response = $client->request(
     'GET',
     'GetCAPMan',
     $this->buildQuery([
         'Database'                 => 'CAR',
         'JustCurrentManufacturers' => 'true',
         'BodyStyleFilter'          => '',
    ])
);

    if ($response->getStatusCode() != 200) {
        return false;
    }

    return $this->parser->xml($response->getBody());

I then include this data into my JSON response like the following

return response()->json(['status' => 'success', 'brands' => $brands]);

This, as I said, works fine.

Now, however, I want to filter the XML response from the external API as I'm not interested in all the fields that it returns. I thought I could use the mask() method but I don't know how.

Since the methods are not fluent I thought I set the mask before parsing the payload, thinking that would apply the mask

$this->parser->mask(['Returned_DataSet' => '*']);

return $this->parser->xml($response->getBody());

But that doesn't work.

This is one reason I want to use this package, the ability to filter the output, but how to do it?

[Nathanmac\Utilities\Parser\Exceptions\ParserException] Failed To Parse XML

I'm trying to parse shoutcast streams file in XSPF format.
Everything works fine but sometimes getting an error:

[Nathanmac\Utilities\Parser\Exceptions\ParserException]
Failed To Parse XML

My XSPF file:

<?xml version="1.0" encoding="utf-8"?>
    <playlist version="1" xmlns="http://xspf.org/ns/0/">
    <title>HARDCORERADIO.NL - Hardcore radio - 24/7 Mainstream Hardcore & Gabber</title>
    <trackList>
        <track>
            <location>http://81.18.165.235:80</location>
            <title>HARDCORERADIO.NL - Hardcore radio - 24/7 Mainstream Hardcore & Gabber</title>
        </track>
        <track>
            <location>http://81.18.165.236:80</location>
            <title>HARDCORERADIO.NL - Hardcore radio - 24/7 Mainstream Hardcore & Gabber</title>
        </track>
        <track>
            <location>http://81.18.165.234:80</location>
            <title>HARDCORERADIO.NL - Hardcore radio - 24/7 Mainstream Hardcore & Gabber</title>
        </track>
    </trackList>
    </playlist>

Stack trace:

[2015-07-10 08:20:17] production.ERROR: exception 'Nathanmac\Utilities\Parser\Exceptions\ParserException' with message 'Failed To Parse XML' in /vagrant/shared/muzza/vendor/nathanmac/parser/src/Formats/XML.php:31
Stack trace:
#0 /vagrant/shared/muzza/vendor/nathanmac/parser/src/Parser.php(193): Nathanmac\Utilities\Parser\Formats\XML->parse('<?xml version="...')
#1 /vagrant/shared/muzza/vendor/nathanmac/parser/src/Parser.php(209): Nathanmac\Utilities\Parser\Parser->parse('<?xml version="...', Object(Nathanmac\Utilities\Parser\Formats\XML))
#2 /vagrant/shared/muzza/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php(208): Nathanmac\Utilities\Parser\Parser->xml('<?xml version="...')
#3 /vagrant/shared/muzza/app/parsers/ShoutCastParser.php(62): Illuminate\Support\Facades\Facade::__callStatic('xml', Array)
#4 /vagrant/shared/muzza/app/parsers/ShoutCastParser.php(62): Nathanmac\Utilities\Parser\Facades\Parser::xml('<?xml version="...')
#5 /vagrant/shared/muzza/app/commands/Streams.php(52): App\Parsers\ShoutCastParser::parseStreamsByStationId()
#6 /vagrant/shared/muzza/vendor/laravel/framework/src/Illuminate/Console/Command.php(112): Streams->fire()
#7 /vagrant/shared/muzza/vendor/symfony/console/Symfony/Component/Console/Command/Command.php(253): Illuminate\Console\Command->execute(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#8 /vagrant/shared/muzza/vendor/laravel/framework/src/Illuminate/Console/Command.php(100): Symfony\Component\Console\Command\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#9 /vagrant/shared/muzza/vendor/symfony/console/Symfony/Component/Console/Application.php(889): Illuminate\Console\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#10 /vagrant/shared/muzza/vendor/symfony/console/Symfony/Component/Console/Application.php(193): Symfony\Component\Console\Application->doRunCommand(Object(Streams), Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#11 /vagrant/shared/muzza/vendor/symfony/console/Symfony/Component/Console/Application.php(124): Symfony\Component\Console\Application->doRun(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#12 /vagrant/shared/muzza/artisan(59): Symfony\Component\Console\Application->run()
#13 {main} [] []

Installation error

I've tried "composer require nathanmac/parser" command, but the command leads to error.
I've been using L5.1

screenshot from 2016-03-17 13 40 04

Read remote XML

Hi,

It's possible to read remote xml and convert it to array ?

Thanks

How to use GET function?

Im using LUMEN.

this work great:
Parser::xml($payload);
But how can i get specific key value using GET function??

cause this, will ALWAYS return default value
Parser::get('Username', 'default value');

XML parsing exception

Hello sir,
I am trying to parse XML response using this library. But while parsing I am having a ParserException in XML.php line 37: 'Failed To Parse XML'.
Thanks in advance.

Content-Type is not detected when the charset is added.

When you send a content type in the form of Content-Type: application/xml; charset=utf8 it will not properly detect the content-type and parse as the default JSON instead.

The problem lies with getFormat where the content-type is directly used to check the supported formats with the content of the header. I therefore propose the Parser::getFormat method gets altered with an explode or strpos to find the first ';' character. My locally used hack is as follows:

if (isset($_SERVER['CONTENT_TYPE']))
{
    $type = explode(';', $_SERVER['CONTENT_TYPE']);
    if (isset($this->supported_formats[$type[0]]))
        return $this->supported_formats[$type[0]];
}
if (isset($_SERVER['HTTP_CONTENT_TYPE']))
{
    $type = explode(';', $_SERVER['HTTP_CONTENT_TYPE']);
    if (isset($this->supported_formats[$type[0]]))
        return $this->supported_formats[$type[0]];
}

This can probably be done more efficiently, but as long as this problem is remedied, I'd love using your library.

composer.lock

Hi there,

Just a thought that it might be worth removing composer.lock from git.

I'm trying to track down a dependency on the now abandoned guzzle/guzzle library, and seeing if it's something I can up to the newer guzzlehttp/guzzle. It probably has no impact ultimately, but I noticed a reference to this in your composer.lock file, but when I run composer update on your library guzzle/guzzle gets replaced with guzzlehttp/guzzle.

laravel 8

Any plans for supporting Laravel 8?

Laravel 5.1 error

Hi,

setting up as shown but get the follwoing error on laravel 5.1 :

Call to undefined method Nathanmac\Utilities\Parser\Facades\Parser::xml()

Thanks Marco

Parsing XML Example

Is it possible to just get a complete example of parsing XML for a specific key using the Facade?

Currently I'm able to convert the whole XML structure into an array using

$xml = Parser::xml($response);

however is there a way to specific pull keys? Using the documentation it would be something like

Parser::get('key', 'default value');

but I don't know how to tie it all together.

Thanks

dependency on symfony/yaml 2.7.* to symfony/yaml ~2.7.*

hi there,
i want to use your package in a laravel 5.1 application. it seems to be that something that laravel uses, requires symfony ~2.8.. Since your package requires 2.7. and NOT ~2.7.* composer cannot import your package.

It would be awesome if you could change that :)

thanks, Leonhard

Failed to parse XML

Hey guys,

I am using the package in a small Laravel Website I am creating for a chess club. Today I ran composer update which was updated the following packages:

  • Symfony/yaml from 3.1.3 to 3.1.4
  • Nathanmac/parser from 4.0 to 4.1
  • Symfony/class-loader from 3.1.3 to 3.1.4
  • Symfony/event-dispatcher from 3.1.3 to 3.1.4

While I was still using parser version 4.0 I was able to import and parse the XML File from [https://ssl-account.com/sbrp-ergebnisdienst.de/index.php?p1=0:ee:BK6-16&style=2]. Therefore I am simply using the following code:

$xml = file_get_contents($url); $xmlArray = Parser::xml($xml);

Unfortunately since I updated the package to 4.1 I get a ParserException in XML.php line 33: Failed To Parse XML. However it was working before and I do not understand the changes.

I would really appreciate your help guys.

Thanks!
Tobias

Class 'Parser' not found

Hi @nathanmac,
I have install nathanmac/parser in xxamp apche, it is working, but when I deploy my project. I have a problem Class 'Parser' not found. I am using laravel 5.1
you can give me any solution to this problem ?
Thank

dependency on symfony/yaml 4.*

Hi there,

I want to use your package in a laravel 5.7.28 application. it seems to be that something that laravel uses, requires symfony ~ 4.. Since your package requires 3., composer cannot import your package.

It would be awesome if you could change that :)

Thanks!

Parsed XML returns empty array

I'm getting this XML from an API call,

<cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'> 
  <cas:authenticationFailure code='INVALID_TICKET'> ticket 'ST-29070-02O0Y6LAcOmMC9ytvddU-cas' not recognized </cas:authenticationFailure> 
</cas:serviceResponse>

When I do

$xml = \Parser::xml( $response->getBody() );
dd($xml);

I just get an ampty array: []

Wondering the cause

How can i edit ParserException

Hi,

First of all great package!
I want to edit de method render() in ParserException.php.
But if i do it probably be overwritten when a new version of this package is been released.

Can anyone tell me how i can exclude this or how to use my own custom ParserException in app/Exceptions?

Thanks in advance!

is this bug?

here is a example:

<?xml version="1.0" encoding="utf-8" ?>
<webcast id="f35e1dc">
    <question id="715da0d" time="1400470679" uid="9934592202" uname="admin">qustion
        <answer id="0e9a009" time="1400470699" uid="1" uname="admin">answer</answer>
    </question>  
</webcast>

use the function xml, then get the following result: [the 'question' is missing]

Array
(
    [@id] => f35e1dc
    [question] => Array
        (
            [@id] => 715da0d
            [@time] => 1400470679
            [@uid] => 9934592202
            [@uname] => admin
            [answer] => Array
                (
                    [#text] => answer
                    [@id] => 0e9a009
                    [@time] => 1400470699
                    [@uid] => 1
                    [@uname] => admin
                )
        )
)

Parser::only('something') does not work?

Good evening,

not sure whether I am simply too stupid but when I apply the only method to my parsed payload the returned array is always null, no matter whether I try to do it via facade (Laravel 5.1) or the OOP way:

\Parser::xml(($response->getBody()->getContents()));
$test = \Parser::only('Order'); // null!
$parser = new Parser();
$orders = $parser->xml(($response->getBody()->getContents()))->only('Order'); // also null

What am I doing wrong? Or is this a bug? :-)

Thanks anyway for the beautiful and easy to use parser!

Andreas

PS: Of course the outputted XML contains a "Order" key on the second level but also "first level" keys do not work

[Question] Get attributes in tags

Hello,

I have :

<enclosure url="http://www.latribunedz.com/Contenu/files/articlesFile/36a4be3a06927e113fa8b19a89377462.jpg" length="" type="image/jpeg" title="" provider="" creator=""/>

Is it possible to get url, type ..etc ?

Thanks

&amp; Validation failed: no DTD found !

Hi there,

I'm using this package for parsing an XML File.
I created a XSD File to validate the XML's structure.

When there are occurences of & entities inside the XML I get the following error while validating the XML File:
Validation failed: no DTD found !

Why does in this case the validation fails? & is a valid entity to use inside a XML document even if no doctype is declared.

I tried declaring one custom doctype, autogenerated by phpstorm, even if I put the dtd file on my webroot the parsing script wasn't able to fetch it. It kept saying that the dtd file could not be found on the given path, even though the file was exactly at the path the error said it wasn't.

Can someone help me?

XML empty field becomes []

Hi,

I don't know wether i'm doing something wrong here or forgetting something but heres the weird thing.
When parsing an .xml file, if a field is empty it gets translated to an empty array, my guess is this is due to a multi-array functionality.

For instance this is my XML:

<?xml version="1.0" encoding="UTF-8"?>
<request>
 <company></company>
 <first_name>Joe</first_name>
 <insertion></insertion>
 <last_name>Dirt</last_name>
 <gender>0</gender>  <!-- 0=male/ 1=female-->
 <street>Somestreet</street>
 <street_number>13</street_number>
 <number_adjective></number_adjective>
 <zipcode>0000AA</zipcode>
 <city>Denver</city>
 <email1>[email protected]</email1>
 <email2></email2>
 <contact_preference>3</contact_preference>  <!-- 1=morning / 2=midday / 3=evening -->
 <home_phone>0123456789</home_phone>
 <mobile>0612345678</mobile>
 <remarks>Some text here</remarks>
 <date>2015-07-03</date>  <!-- MySQL date format -->
 <source_id>1</source_id> <!-- Internal unique number from supplier -->
 <source_api>1234567890</source_api> <!-- API key -->
</request>

I am loading it with: $xml = Parser::xml(File::get($filename));
when doing a dd($xml); it gives me something like:

company = []
first_name = Joe
insertion = []
last_name = Dirt
gender = 0
street = Somestreet
street_number = 13
etc.

When inserting it in the database i get values named Array.

Is there any easy way for me to force empty fields to empty instead of array types?

Laravel 7 support

When you try to install Parser on Laravel 7 Composer output is:

Problem 1
    - Conclusion: don't install laravel/framework v7.0.4
    - Conclusion: don't install laravel/framework v7.0.3
    - Conclusion: don't install laravel/framework v7.0.2
    - Conclusion: don't install laravel/framework v7.0.1
    - Conclusion: don't install laravel/framework v7.0.0
    - Conclusion: remove nathanmac/parser v4.3
    - Conclusion: don't install nathanmac/parser v4.3|don't install symfony/routing v5.0.5|keep symfony/yaml v3.4.38
    - Conclusion: don't install nathanmac/parser v4.3|don't install symfony/routing v5.0.4|keep symfony/yaml v3.4.38
    - Conclusion: don't install nathanmac/parser v4.3|don't install symfony/routing v5.0.3|keep symfony/yaml v3.4.38
    - Conclusion: don't install nathanmac/parser v4.3|don't install symfony/routing v5.0.2|keep symfony/yaml v3.4.38
    - Conclusion: don't install nathanmac/parser v4.3|don't install symfony/routing v5.0.1|keep symfony/yaml v3.4.38
    - Conclusion: remove symfony/yaml v3.4.38
    - Conclusion: don't install symfony/routing v5.0.0
    - Conclusion: don't install symfony/yaml v3.4.38
    - Conclusion: don't install symfony/routing v5.0.0-RC1
    - Conclusion: don't install symfony/yaml v3.4.37
    - Conclusion: don't install symfony/routing v5.0.0-BETA2
    - Conclusion: don't install symfony/yaml v3.4.36
    - Conclusion: don't install symfony/routing v5.0.0-BETA1
    - Conclusion: don't install symfony/yaml v3.4.35
    - Installation request for nathanmac/parser ^4.3 -> satisfiable by nathanmac/parser[v4.3].
    - Installation request for laravel/framework ^7.0 -> satisfiable by laravel/framework[7.x-dev, v7.0.0, v7.0.1, v7.0.2, v7.0.3, v7.0.4].
    - nathanmac/parser v4.3 requires symfony/yaml ~2.0|~3.0 -> satisfiable by symfony/yaml[v3.4.38, 2.0.4, 2.0.5, 2.0.6, 2.0.7, 2.0.x-dev, 2.1.x-dev, 2.2.x-dev, 2.3.x-dev, 2.4.x-dev, 2.5.x-dev, 2.6.x-dev, 2.7.x-dev, 2.8.x-dev, 3.0.x-dev, 3.1.x-dev, 3.2.x-dev, 3.3.x-dev, 3.4.x-dev, v2.0.10, v2.0.12, v2.0.13, v2.0.14, v2.0.15, v2.0.16, v2.0.17, v2.0.18, v2.0.19, v2.0.20, v2.0.21, v2.0.22, v2.0.23, v2.0.24, v2.0.25, v2.0.9, v2.1.0, v2.1.1, v2.1.10, v2.1.11, v2.1.12, v2.1.13, v2.1.2, v2.1.3, v2.1.4, v2.1.5, v2.1.6, v2.1.7, v2.1.8, v2.1.9, v2.2.0, v2.2.1, v2.2.10, v2.2.11, v2.2.2, v2.2.3, v2.2.4, v2.2.5, v2.2.6, v2.2.7, v2.2.8, v2.2.9, v2.3.0, v2.3.1, v2.3.10, v2.3.11, v2.3.12, v2.3.13, v2.3.14, v2.3.15, v2.3.16, v2.3.17, v2.3.18, v2.3.19, v2.3.2, v2.3.20, v2.3.21, v2.3.22, v2.3.23, v2.3.24, v2.3.25, v2.3.26, v2.3.27, v2.3.28, v2.3.29, v2.3.3, v2.3.30, v2.3.31, v2.3.32, v2.3.33, v2.3.34, v2.3.35, v2.3.36, v2.3.37, v2.3.38, v2.3.39, v2.3.4, v2.3.40, v2.3.41, v2.3.42, v2.3.5, v2.3.6, v2.3.7, v2.3.8, v2.3.9, v2.4.0, v2.4.0-BETA1, v2.4.0-BETA2, v2.4.0-RC1, v2.4.1, v2.4.10, v2.4.2, v2.4.3, v2.4.4, v2.4.5, v2.4.6, v2.4.7, v2.4.8, v2.4.9, v2.5.0, v2.5.0-BETA1, v2.5.0-BETA2, v2.5.0-RC1, v2.5.1, v2.5.10, v2.5.11, v2.5.12, v2.5.2, v2.5.3, v2.5.4, v2.5.5, v2.5.6, v2.5.7, v2.5.8, v2.5.9, v2.6.0, v2.6.0-BETA1, v2.6.0-BETA2, v2.6.1, v2.6.10, v2.6.11, v2.6.12, v2.6.13, v2.6.2, v2.6.3, v2.6.4, v2.6.5, v2.6.6, v2.6.7, v2.6.8, v2.6.9, v2.7.0, v2.7.0-BETA1, v2.7.0-BETA2, v2.7.1, v2.7.10, v2.7.11, v2.7.12, v2.7.13, v2.7.14, v2.7.15, v2.7.16, v2.7.17, v2.7.18, v2.7.19, v2.7.2, v2.7.20, v2.7.21, v2.7.22, v2.7.23, v2.7.24, v2.7.25, v2.7.26, v2.7.27, v2.7.28, v2.7.29, v2.7.3, v2.7.30, v2.7.31, v2.7.32, v2.7.33, v2.7.34, v2.7.35, v2.7.36, v2.7.37, v2.7.38, v2.7.39, v2.7.4, v2.7.40, v2.7.41, v2.7.42, v2.7.43, v2.7.44, v2.7.45, v2.7.46, v2.7.47, v2.7.48, v2.7.49, v2.7.5, v2.7.50, v2.7.51, v2.7.6, v2.7.7, v2.7.8, v2.7.9, v2.8.0, v2.8.0-BETA1, v2.8.1, v2.8.10, v2.8.11, v2.8.12, v2.8.13, v2.8.14, v2.8.15, v2.8.16, v2.8.17, v2.8.18, v2.8.19, v2.8.2, v2.8.20, v2.8.21, v2.8.22, v2.8.23, v2.8.24, v2.8.25, v2.8.26, v2.8.27, v2.8.28, v2.8.29, v2.8.3, v2.8.30, v2.8.31, v2.8.32, v2.8.33, v2.8.34, v2.8.35, v2.8.36, v2.8.37, v2.8.38, v2.8.39, v2.8.4, v2.8.40, v2.8.41, v2.8.42, v2.8.43, v2.8.44, v2.8.45, v2.8.46, v2.8.47, v2.8.48, v2.8.49, v2.8.5, v2.8.50, v2.8.52, v2.8.6, v2.8.7, v2.8.8, v2.8.9, v3.0.0, v3.0.0-BETA1, v3.0.1, v3.0.2, v3.0.3, v3.0.4, v3.0.5, v3.0.6, v3.0.7, v3.0.8, v3.0.9, v3.1.0, v3.1.0-BETA1, v3.1.0-RC1, v3.1.1, v3.1.10, v3.1.2, v3.1.3, v3.1.4, v3.1.5, v3.1.6, v3.1.7, v3.1.8, v3.1.9, v3.2.0, v3.2.0-BETA1, v3.2.0-RC1, v3.2.0-RC2, v3.2.1, v3.2.10, v3.2.11, v3.2.12, v3.2.13, v3.2.14, v3.2.2, v3.2.3, v3.2.4, v3.2.5, v3.2.6, v3.2.7, v3.2.8, v3.2.9, v3.3.0, v3.3.0-BETA1, v3.3.0-RC1, v3.3.1, v3.3.10, v3.3.11, v3.3.12, v3.3.13, v3.3.14, v3.3.15, v3.3.16, v3.3.17, v3.3.18, v3.3.2, v3.3.3, v3.3.4, v3.3.5, v3.3.6, v3.3.7, v3.3.8, v3.3.9, v3.4.0, v3.4.0-BETA1, v3.4.0-BETA2, v3.4.0-BETA3, v3.4.0-BETA4, v3.4.0-RC1, v3.4.0-RC2, v3.4.1, v3.4.10, v3.4.11, v3.4.12, v3.4.13, v3.4.14, v3.4.15, v3.4.16, v3.4.17, v3.4.18, v3.4.19, v3.4.2, v3.4.20, v3.4.21, v3.4.22, v3.4.23, v3.4.24, v3.4.25, v3.4.26, v3.4.27, v3.4.28, v3.4.29, v3.4.3, v3.4.30, v3.4.31, v3.4.32, v3.4.33, v3.4.34, v3.4.35, v3.4.36, v3.4.37, v3.4.4, v3.4.5, v3.4.6, v3.4.7, v3.4.8, v3.4.9].
    - symfony/yaml 2.0.4 conflicts with symfony/routing[5.0.x-dev].
    - symfony/yaml 2.0.5 conflicts with symfony/routing[5.0.x-dev].
    - symfony/yaml 2.0.6 conflicts with symfony/routing[5.0.x-dev].
    - symfony/yaml 2.0.7 conflicts with symfony/routing[5.0.x-dev].
    - symfony/yaml 2.0.x-dev conflicts with symfony/routing[5.0.x-dev].
    - symfony/yaml 2.1.x-dev conflicts with symfony/routing[5.0.x-dev].
    - symfony/yaml 2.2.x-dev conflicts with symfony/routing[5.0.x-dev].
    - symfony/yaml 2.3.x-dev conflicts with symfony/routing[5.0.x-dev].
    - symfony/yaml 2.4.x-dev conflicts with symfony/routing[5.0.x-dev].

Because Laravel 7 uses Symfony packages version 5.

XML looses attributes when parsed

Thank you for this great tool.

I really hope I haven't overlooked this, but I have an XML as follows:

<extension point="whatever">
   <summary lang="bg">FAFSSAFA</summary>
   <summary lang="ca">OIGOIEWG</summary>
   <summary lang="cs">KGJWOIGJW</summary>
</extension>

So if I parse it, I can get the attributes of the extension. But summary gets grouped to an array and the attributes (bg, ca, cs) get lost.

[@attributes] => Array
    (
        [point] => whatever
    )

[summary] => Array
    (
        [0] => FAFSSAFA
        [1] => OIGOIEWG
        [2] => KGJWOIGJW
    )

Bug or feature? XML reply with 1 entry behaves differently with n entries

Good morning,

I am not sure whether this is a bug or a feature or if I am using Parser in a wrong way.

Take the following XML:

<?xml version="1.0"?>
<GetFeedSubmissionListResponse xmlns="http://mws.amazonaws.com/doc/2009-01-01/">
  <GetFeedSubmissionListResult>
    <HasNext>false</HasNext>
    <FeedSubmissionInfo>
      <FeedProcessingStatus>_IN_PROGRESS_</FeedProcessingStatus>
      <FeedType>_POST_FBA_INBOUND_CARTON_CONTENTS_</FeedType>
      <FeedSubmissionId>40737016817</FeedSubmissionId>
      <StartedProcessingDate>2016-01-17T21:13:27+00:00</StartedProcessingDate>
      <SubmittedDate>2016-01-17T21:12:53+00:00</SubmittedDate>
    </FeedSubmissionInfo>
    <FeedSubmissionInfo>
      <FeedProcessingStatus>_DONE_</FeedProcessingStatus>
      <FeedType>_POST_FBA_INBOUND_CARTON_CONTENTS_</FeedType>
      <FeedSubmissionId>40736016817</FeedSubmissionId>
      <StartedProcessingDate>2016-01-17T21:12:38+00:00</StartedProcessingDate>
      <SubmittedDate>2016-01-17T21:12:06+00:00</SubmittedDate>
      <CompletedProcessingDate>2016-01-17T21:13:13+00:00</CompletedProcessingDate>
    </FeedSubmissionInfo>
    <FeedSubmissionInfo>
      <FeedProcessingStatus>_DONE_</FeedProcessingStatus>
      <FeedType>_POST_FBA_INBOUND_CARTON_CONTENTS_</FeedType>
      <FeedSubmissionId>40735016817</FeedSubmissionId>
      <StartedProcessingDate>2016-01-17T21:07:07+00:00</StartedProcessingDate>
      <SubmittedDate>2016-01-17T21:07:01+00:00</SubmittedDate>
      <CompletedProcessingDate>2016-01-17T21:07:53+00:00</CompletedProcessingDate>
    </FeedSubmissionInfo>
    <FeedSubmissionInfo>
      <FeedProcessingStatus>_DONE_</FeedProcessingStatus>
      <FeedType>_POST_FBA_INBOUND_CARTON_CONTENTS_</FeedType>
      <FeedSubmissionId>40734016817</FeedSubmissionId>
      <StartedProcessingDate>2016-01-17T19:04:13+00:00</StartedProcessingDate>
      <SubmittedDate>2016-01-17T19:03:55+00:00</SubmittedDate>
      <CompletedProcessingDate>2016-01-17T19:04:54+00:00</CompletedProcessingDate>
    </FeedSubmissionInfo>
  </GetFeedSubmissionListResult>
  <ResponseMetadata>
    <RequestId>608dc493-ca8a-4b4d-99a5-7775269e2ac6</RequestId>
  </ResponseMetadata>
</GetFeedSubmissionListResponse>

If I parse this using

$responseItems = $requestStatus->parsedResponse['GetFeedSubmissionListResult']['FeedSubmissionInfo'];

my $responseItems contain an array of four items from $responseItems[0] to $responseItems[3] where I can access all attributes like FeedSubmissionId for example like $responseItems[1]['FeedSubmissionId'] - perfect.

However, if the XML response only has ONE FeedSubmissionInfo item, like this:

<?xml version="1.0"?>
<GetFeedSubmissionListResponse xmlns="http://mws.amazonaws.com/doc/2009-01-01/">
  <GetFeedSubmissionListResult>
    <HasNext>false</HasNext>
    <FeedSubmissionInfo>
      <FeedProcessingStatus>_IN_PROGRESS_</FeedProcessingStatus>
      <FeedType>_POST_FBA_INBOUND_CARTON_CONTENTS_</FeedType>
      <FeedSubmissionId>40737016817</FeedSubmissionId>
      <StartedProcessingDate>2016-01-17T21:13:27+00:00</StartedProcessingDate>
      <SubmittedDate>2016-01-17T21:12:53+00:00</SubmittedDate>
    </FeedSubmissionInfo>
  </GetFeedSubmissionListResult>
  <ResponseMetadata>
    <RequestId>608dc493-ca8a-4b4d-99a5-7775269e2ac6</RequestId>
  </ResponseMetadata>
</GetFeedSubmissionListResponse>

Then $responseItems[0]['FeedSubmissionId'] throws an illegal offset error, since the parser (of course?) parsed the response not like $responseItems[0]['FeedSubmissionId'] but like this: $responseItems['FeedSubmissionId'].

Now I am wondering if this is a bug or works as designed?

And what would be the workaround? Convert the whole xml to a collection and then work with that?

Thanks
Andreas

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.