项目作者: alguive

项目描述 :
Easy way to convert from XML to Array
高级语言: PHP
项目地址: git://github.com/alguive/xmltoarray.git
创建时间: 2019-02-22T18:49:53Z
项目社区:https://github.com/alguive/xmltoarray

开源协议:

下载


Convert Xml to Array

A simply way to convert from XML to Array.

  1. $xmlPath = 'filepath';
  2. $xmlToArray = new \Alvaro\Xmltoarray\XmlParser($xmlPath);
  3. $arrayResult = $xmlToArray->parse();
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <COUNTRIES>
  3. <COUNTRY>
  4. <NAME>SPAIN</NAME>
  5. <CAPITAL>MADRID</CAPITAL>
  6. </COUNTRY>
  7. <COUNTRY>
  8. <NAME>GERMANY</NAME>
  9. <CAPITAL>BERLIN</CAPITAL>
  10. </COUNTRY>
  11. </COUNTRIES>

This will retrieve:

  1. $array = [
  2. "COUNTRIES" => [
  3. "COUNTRY" => [
  4. 0 => [
  5. "NAME" => "SPAIN"
  6. "CAPITAL" => "MADRID"
  7. ],
  8. 1 => [
  9. "NAME" => "GERMANY"
  10. "CAPITAL" => "BERLIN"
  11. ]
  12. ]
  13. ]
  14. ]

Set custom root key

  1. $xmlToArray = new \Alvaro\Xmltoarray\XmlParser($xmlPath);
  2. $xmlToArray->setRootElementText('TEST');
  3. $arrayResult = $xmlToArray->parse();

This will retrieve:

  1. $array = [
  2. "TEST" => [
  3. "COUNTRY" => [
  4. 0 => [
  5. "NAME" => "SPAIN"
  6. "CAPITAL" => "MADRID"
  7. ],
  8. 1 => [
  9. "NAME" => "GERMANY"
  10. "CAPITAL" => "BERLIN"
  11. ]
  12. ]
  13. ]
  14. ]

Without root element

  1. $xmlToArray = new \Alvaro\Xmltoarray\XmlParser($xmlPath);
  2. $xmlToArray->includeRootElement(false);
  3. $arrayResult = $xmlToArray->parse();

This will retrieve:

  1. $array = [
  2. "COUNTRY" => [
  3. 0 => [
  4. "NAME" => "SPAIN"
  5. "CAPITAL" => "MADRID"
  6. ],
  7. 1 => [
  8. "NAME" => "GERMANY"
  9. "CAPITAL" => "BERLIN"
  10. ]
  11. ]
  12. ]

Get the root element name

  1. $xmlToArray = new \Alvaro\Xmltoarray\XmlParser($xmlPath);
  2. $rootElement = $xmlToArray->getRootElementText(false);

This will retrieve:

  1. COUNTRIES


Made with ❤️ in BCN