Created
August 19, 2022 13:26
-
-
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!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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