Skip to content

Instantly share code, notes, and snippets.

@michitheonlyone
Created August 19, 2022 13:26
Show Gist options
  • Save michitheonlyone/a0066ee13a9ee047063d8839295e9501 to your computer and use it in GitHub Desktop.
Save michitheonlyone/a0066ee13a9ee047063d8839295e9501 to your computer and use it in GitHub Desktop.
PHP XMLReader - Composed of SimpleXMLElement to convert XML to Array - do not use for large xml!
<?php declare(strict_types=1);
namespace App\Util;
final class XMLReader
{
private \SimpleXMLElement $XMLElement;
/**
* @param string $xmlString A well-formed XML string of any resource
* @throws \InvalidArgumentException if string is not valid XML or well-formed
*/
public function __construct(string $xmlString)
{
try {
$this->XMLElement = simplexml_load_string($xmlString);
} catch (\Exception $exception) {
throw new \InvalidArgumentException($exception->getMessage());
}
}
public static function fromXmlString(string $xmlString): self
{
return new self($xmlString);
}
public function toJson(): string
{
return json_encode($this->XMLElement);
}
public function toArray(): array
{
return json_decode($this->toJson(), true);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment