PHP code example of donatorsky / php-xml-template-reader
1. Go to this page and download the library: Download donatorsky/php-xml-template-reader library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
donatorsky / php-xml-template-reader example snippets
Node {
private $nodeName = 'books';
private $children = Map [
// Because of tpl:type="collection", book element is expected to occur more than 1 times
'book' => Collection [
0 => Node {
private $nodeName = 'book';
private $attributes = Map [
// You can define set of parsing rules in the template. In this case:
// 1 time
private $relations = Map [
'title' => Node {
private $nodeName = 'title';
private $contents = 'Lorem ipsum adventures';
},
...
];
},
1 => ...
]
];
}
$xmlTemplateReader = new \Donatorsky\XmlTemplate\Reader\XmlTemplateReader(<<<'XML'
<?xml version="1.0" encoding="UTF-8"
namespace Some\Name\Space;
class BooksNode implements \Donatorsky\XmlTemplate\Reader\Models\Contracts\NodeInterface {
// ...
}
// You can also extend \Donatorsky\XmlTemplate\Reader\Models\Node class
class SingleBookNode extends \Donatorsky\XmlTemplate\Reader\Models\Node {
// ...
public function getIsbn(): int {
return $this->attributes->get('ISBN');
}
public function getCategory(): int {
return $this->attributes->get('category');
}
}
$booksNode = Some\Name\Space\BooksNode {
private $nodeName = 'books';
private $children = \Donatorsky\XmlTemplate\Reader\Models\Map [
// Because of tpl:type="collection", book element is expected to occur more than 1 times
'book' => \Donatorsky\XmlTemplate\Reader\Models\Collection [
0 => Some\Name\Space\SingleBookNode {
private $nodeName = 'book';
private $attributes = \Donatorsky\XmlTemplate\Reader\Models\Map [
// You can define set of parsing rules in the template. In this case:
// private $nodeName = 'title';
private $contents = 'Lorem ipsum adventures';
},
...
];
},
1 => ...
]
];
}
// ...
/**
* @var \Some\Name\Space\SingleBookNode $book
*/
foreach ($booksNode->getChildren('book') as $book){
var_dump($book->getIsbn(), $book->getCategory());
}
Node {
private $nodeName = 'books';
private $attributes = \Donatorsky\XmlTemplate\Reader\Models\Map [
'ISBN' => '1234567890',
// 'category' is missing as it is not "validated"
];
}
namespace Some\Name\Space;
class RegexpRule implements \Donatorsky\XmlTemplate\Reader\Rules\Contracts\RuleInterface {
private string $pattern;
public function __construct(string $pattern) {
$this->pattern = $pattern;
}
public function passes($value) : bool {
// Validate $value against pattern
return (bool) preg_match($this->pattern, $value);
}
public function process($value) {
// Do not modify value
return $value;
}
}