PHP code example of sbwerewolf / xml-navigator

1. Go to this page and download the library: Download sbwerewolf/xml-navigator 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/ */

    

sbwerewolf / xml-navigator example snippets


use SbWereWolf\XmlNavigator\Parsing\FastXmlParser;

t-');
file_put_contents(
    $uri,
    <<<XML
<?xml version="1.0" encoding="UTF-8"

array (
  'n' => 'offer',
  'a' =>
  array (
    'id' => '1001',
    'available' => 'true',
  ),
  's' =>
  array (
    0 =>
    array (
      'n' => 'name',
      'v' => 'Keyboard',
    ),
    1 =>
    array (
      'n' => 'price',
      'v' => '49.90',
      'a' =>
      array (
        'currency' => 'USD',
      ),
    ),
  ),
)
array (
  'n' => 'offer',
  'a' =>
  array (
    'id' => '1002',
    'available' => 'false',
  ),
  's' =>
  array (
    0 =>
    array (
      'n' => 'name',
      'v' => 'Mouse',
    ),
    1 =>
    array (
      'n' => 'price',
      'v' => '19.90',
      'a' =>
      array (
        'currency' => 'USD',
      ),
    ),
  ),
)

use SbWereWolf\XmlNavigator\Conversion\XmlConverter;

 attr: 'attributes',
    name: 'name',
    seq: 'children',
);

$hierarchy = $converter->toHierarchyOfElements(
    '<price currency="USD">129.90</price>'
);

var_export($hierarchy);

array (
  'name' => 'price',
  'value' => '129.90',
  'attributes' =>
  array (
    'currency' => 'USD',
  ),
)

use SbWereWolf\XmlNavigator\Parsing\FastXmlParser;

t-');
file_put_contents(
    $uri,
    <<<'XML'
<?xml version="1.0" encoding="UTF-8"

use SbWereWolf\XmlNavigator\Conversion\FastXmlToArray;
use SbWereWolf\XmlNavigator\Navigation\XmlElement;

<tag>office</tag>
    <tag>usb</tag>
  </offer>
</catalog>
XML;

$root = new XmlElement(FastXmlToArray::convert($xml));
$offer = $root->pull('offer')->current();

echo $root->name() . PHP_EOL;                // catalog
echo $root->get('region') . PHP_EOL;         // eu
echo ($root->hasElement('offer') ? 'yes' : 'no') . PHP_EOL; // yes

echo PHP_EOL;
echo 'offer attributes:' . PHP_EOL;
foreach ($offer->attributes() as $attribute) {
    echo $attribute->name() . '=' . $attribute->value() . PHP_EOL;
}

echo PHP_EOL;
echo 'offer elements with name `tag`:' . PHP_EOL;
$tagValues = array_map(
    static fn (XmlElement $tag): string => $tag->value(),
    $offer->elements('tag')
);

var_export($tagValues);
text
large XML → selected nodes → plain PHP arrays