PHP code example of joeycumines / simple-xml-util

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

    

joeycumines / simple-xml-util example snippets


// manual configuration example

use JoeyCumines\SimpleXmlUtil\Parser\SimpleXmlStringParser;

// ...

$xmlParser = new SimpleXmlStringParser($className, $options, $ns, $prefix, $disableEntityLoader);

// or

$xmlParser = (new SimpleXmlStringParser())
    ->setClassName($className)
    ->setOptions($options)
    ->setNs($ns)
    ->setPrefix($prefix)
    ->setDisableEntityLoader($disableEntityLoader);


// use the interface in the service - pre-configured

use JoeyCumines\SimpleXmlUtil\Exception\SimpleXmlStringParserException;
use JoeyCumines\SimpleXmlUtil\Interfaces\SimpleXmlStringParserInterface;

// ...

class SomeService
{
    private $xmlParser;
    private $logger;

    public function __construct(
        SimpleXmlStringParserInterface $xmlParser,
        Logger $logger
    ) {
        $this->xmlParser = $xmlParser;
        $this->logger = $logger;
    }
    
    public function doSomeXmlParsing(string $data): array
    {
        try {
            $doc = $this->xmlParser->parseXmlString($data);
        } catch (SimpleXmlStringParserException $e) {
            // the actual parser error will come through in the logs
            $this->logger->error(
                "[SomeService] o no our xml things failed:\n{$e}",
                $e
            );
            
            throw $e;
        }
        
        // at this point you can always be sure $doc is an actual object
        
        foreach ($doc as $name => $child) {
            // ...
        }
        
        // ...
    }
}