Php simplexml в массиве

jasondmoss / simpleXmlToArray.php

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

/**
* Convert a SimpleXML object to an associative array
*
* @param object $xmlObject
*
* @return array
* @access public
*/
function simpleXmlToArray ( $ xmlObject )
$ array = [];
foreach ( $ xmlObject -> children () as $ node )
$ array [ $ node -> getName ()] = is_array( $ node ) ? simplexml_to_array( $ node ) : ( string ) $ node ;
>
return $ array ;
>

Thanks for having this when even stack overflow couldn’t help, saved me quite a headache

is_array($node) returned false for me, so it only gave me results one layer down

The enhanced version, with recursive children

 function simpleXmlToArray($xmlObject) < $array = []; foreach ($xmlObject->children() as $node) < // check if there are children if($node->count() > 0) < $array[$node->getName()] = simpleXmlToArray($node); continue; > $array[$node->getName()] = is_array($node) ? simplexml_to_array($node) : (string) $node; > return $array; > 

In few cases, an XML object can be in a form as showed below:

In this case, the good enhanced function simpleXmlToArray() proposed by @feldsam transforms the XML in an array nesting all the sameParentNode’s sons but it’s not able to convert the recursive SimpleXMLElement because of getting an absent node name. This causes it pushes in the array just last recursiveSon node, overwriting all the others previous.

[sameParentNode] => Array ( [0] => SimpleXMLElement Object (lastRecursiveNodes) ( . ) ) 

So, I propose a new version with an if condition on recursive nodes that keeps the not-associative nodes in the transfomed array:

function simpleXmlToArray($xmlObject) < $array = []; $c=0; foreach ($xmlObject->children() as $node) < // Here the new if: check if children don't have a node name keeping them in the new structure as not-associative nodes if($node->children()->count() > 0) < $array[$node->getName()][] = simpleXmlToArray($node); > else < $array[$node->getName()] = (string) $node; > > return $array; > 

Thanks everybody for chipping in here. I have taken the version from @MarcelloDM and added attributes support and nested nodes are not always added under a numeric value but directly under it’s parent name.

function simpleXmlToArray(SimpleXMLElement $xmlObject): array < $array = []; foreach ($xmlObject->children() as $node) < $attributes = []; if ($node->attributes()) < foreach ($node->attributes() as $name => $value) < $attributes[$name] = (string)$value; >> if ($node->children()->count() > 0) < $data = array_merge($attributes, $this->simpleXmlToArray($node)); if (isset($array[$node->getName()])) < if (!isset($array[$node->getName()][0])) < $entry = $array[$node->getName()]; $array[$node->getName()] = []; $array[$node->getName()][] = $entry; > $array[$node->getName()][] = $data; > else < $array[$node->getName()] = $data; > > else < $array[$node->getName()] = (string)$node; > > return $array; > 
 /** * @param $xml * @return array * https://hotexamples.com/examples/-/-/simplexml_to_array/php-simplexml_to_array-function-examples.html */ public static function simplexmlToArray($xml) < $ar = array(); foreach ($xml->children() as $k => $v) < $child = self::simplexmlToArray($v); if (count($child) == 0) < $child = (string) $v; >foreach ($v->attributes() as $ak => $av) < if (!is_array($child)) < $child = array("value" =>$child); > $child[$ak] = (string) $av; > if (!array_key_exists($k, $ar)) < $ar[$k] = $child; >else < if (!is_string($ar[$k]) && isset($ar[$k][0])) < $ar[$k][] = $child; >else < $ar[$k] = array($ar[$k]); $ar[$k][] = $child; >> > return $ar; > 

Источник

Parse XML to an Array in PHP With SimpleXML

Sajal Soni

Sajal Soni Last updated Aug 12, 2020

In this post, you’ll learn how to parse XML into an array in PHP. SimpleXML is a PHP extension that makes this possible.

In your day-to-day PHP development, sometimes you’ll need to deal with XML content. Whether it’s exporting data as XML documents or processing incoming XML documents in your application, it’s always handy to have a library that can perform these operations smoothly. When it comes to dealing with XML in PHP, there are different methods to choose from. In fact, there are different extensions available in PHP that allow you to read and parse XML documents.

PHP’s XML parser is based on James Clark’s expat library, which is a stream-oriented XML library written in C. This XML parser library allows you to parse XML documents, but it’s not able to validate them. It’s event-based and stream-oriented, and thus it’s really useful when you’re dealing with very large XML files—but a little more complicated than it needs to be for small files.

The other option is the SimpleXML extension, which is one of the most popular extensions used by the PHP community to process XML documents. The SimpleXML extension allows you to parse XML documents very easily, just as if you were reading a file in PHP.

In this article, we’re going to use the SimpleXML extension to demonstrate how you could convert XML content into an array. If you want to follow along with the example in this article, make sure that you’ve installed the SimpleXML extension in your PHP installation.

The SimpleXML PHP Extension

The SimpleXML PHP extension provides a complete toolset which you can use to read, write and parse XML documents in your PHP applications. It’s important to note that the SimpleXML extension requires PHP 5 at a minimum. Also, it requires the libxml PHP extension.

The SimpleXML extension is enabled by default, but if you want to check if it’s enabled in your PHP installation, you can check it quickly by using the phpinfo() function.

The phpinfo Function

As you can see, you should see the SimpleXML section in the output of the phpinfo() function.

The SimpleXML extension provides different functions that you could use to read and parse XML content.

Loading an XML String or File With SimpleXML

For example, if you want to parse the XML file, you can use the simplexml_load_file() function. The simplexml_load_file() function allows you to read and parse the XML file in a single call. On the other hand, if you have an XML string which you want to convert into an XML document object, you can use the simplexml_load_string() function.

You could also use the file_get_contents() function to read the file contents and pass the resulting string to the simplexml_load_string() function, which eventually parses it into an object. Alternatively, if you prefer the object-oriented way, you could also use the SimpleXMLElement class and its utility methods to convert an XML string into an object.

In this article, we’re going to use the simplexml_load_file() function to read an XML file, and we’ll see how to convert it into an array. Next, we’ll go through a real-world example to demonstrate how to do this.

How to Convert XML to an Array With PHP

In this section, we’ll see how you can convert XML content into an array.

First of all, let’s quickly go through the steps that you need to follow to convert XML content into an array with the help of the SimpleXML extension.

  • Read the file contents and parse them. At the end of this step, the content is parsed and converted into the SimpleXMLElement object format. We’re going to use the simplexml_load_file() function to achieve this.
  • Next, you need to convert the SimpleXMLElement object into a JSON representation by using the json_encode() function.
  • Finally, you need to use the json_decode() function to decode the JSON content so that it eventually generates an array of all documents.

For demonstration purposes, let’s assume that we have an XML file as shown in the following snippet. We’ll call it employees.xml. It contains the basic details of all employees. Our aim is to convert it into an array that you could use for further processing.

Источник

PHP SimpleXML. Парсинг XML в массив

Расширение PHP SimpleXML разбирает XML в масcив. SimpleXML имеет полный набор инструментов, которые позволяют читать, писать и анализировать XML-документ. Расширение SimpleXML требует минимальную версию PHP 5 и расширение PHP libxml.

Расширение PHP SimpleXML включено по умолчанию, проверить это можно с помощью функции phpinfo():

Как преобразовать XML в массив с помощью PHP

Для примера возьмем такой XML документ:

   Box  30.00 
3030 Info Avenue Los Angeles CA
New box 50.00
3040 Info Road Duluth GA

Преобразуем XML в массив PHP. Для этого загружаем строку с XML в simplexml_load_string(), в ответ получим ассоциативный массив:

   Box  30.00 
3030 Info Avenue Los Angeles CA
New box 50.00
3040 Info Road Duluth GA
"; libxml_use_internal_errors(TRUE); //Используем simplexml_load_file(), если нужно распарсить файл //$objXmlDocument = simplexml_load_file("pathToFile.xml"); //Используем simplexml_load_string(), если нужно распарсить строку $objXmlDocument = simplexml_load_string($xml); if ($objXmlDocument === FALSE) < echo "There were errors parsing the XML file.\n"; foreach(libxml_get_errors() as $error) < echo $error->message; > exit; > $objJsonDocument = json_encode($objXmlDocument); $arrOutput = json_decode($objJsonDocument, TRUE); echo "
"; print_r($arrOutput); echo "

"; foreach ($arrOutput['item'] as $arrOutputKey => $arrOutputValue) < echo $arrOutputValue['@attributes']['id'] . ' - ' .$arrOutputValue['name'] . '
'; >

Пример выполнения скрипта:

Array ( [item] => Array ( [0] => Array ( [@attributes] => Array ( [id] => 1 ) [name] => Box [year] => 2021 [price] => 30.00 [address] => Array ( [street] => 3030 Info Avenue [city] => Los Angeles [state] => CA ) ) [1] => Array ( [@attributes] => Array ( [id] => 2 ) [name] => New box [year] => 2022 [price] => 50.00 [address] => Array ( [street] => 3040 Info Road [city] => Duluth [state] => GA ) ) ) ) 1 - Box 2 - New box

Web разработчик, специализируюсь на разработке full stack веб-приложений.
Если у вас есть предложения или вопросы свяжитесь со мной: facebook

Источник

Читайте также:  Php variable variables uses
Оцените статью