Php xml response to array

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.

Читайте также:  Php создание zip архивов

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.

Источник

xml_parse_into_struct

Эта функция разбирает XML строку и помещает данные в 2 массива. Массив index содержит указатели на размещение значений в массиве values . Аргументы, задающие массивы, должны передаваться в функцию по ссылке.

Список параметров

Ссылка на используемый XML анализатор.

Массив значений XML данных.

Массив указателей на соответствующие значения в массиве $values.

Возвращаемые значения

xml_parse_into_struct() возвращает 0 при неудачном разборе строки и 1 при успешном. Это не тоже самое, что FALSE и TRUE , будьте осторожны с такими операторами, как ===.

Примеры

Ниже представлен пример, демонстрирующий внутреннее устройство массивов, генерируемых функцией. XML строка содержит простой тэг note вложенный в тэг para. Программа в примере разбирает эту строку и выводит построенные массивы:

Пример #1 Пример использования xml_parse_into_struct()

$simple = «simple note» ;
$p = xml_parser_create ();
xml_parse_into_struct ( $p , $simple , $vals , $index );
xml_parser_free ( $p );
echo «Index array\n» ;
print_r ( $index );
echo «\nМассив Vals\n» ;
print_r ( $vals );
?>

После обработки программа выведет следующее:

Index array Array ( [PARA] => Array ( [0] => 0 [1] => 2 ) [NOTE] => Array ( [0] => 1 ) ) Массив Vals Array ( [0] => Array ( [tag] => PARA [type] => open [level] => 1 ) [1] => Array ( [tag] => NOTE [type] => complete [level] => 2 [value] => simple note ) [2] => Array ( [tag] => PARA [type] => close [level] => 1 ) )

Управляемый событиями разбор (основанный на expat библиотеке) может дать труднообрабатываемый результат в случае, если разбирается составной XML документ. Эта функция не создает DOM объектов, но создаваемые ею массивы можно преобразовать в древовидную структуру впоследствии. Таким образом можно довольно просто создавать объекты, представляющие содержимое XML файла. Предположим, что следующий XML файл представляет небольшую базу данных с информацией об аминокислотах:

Пример #2 moldb.xml — небольшая база данных с информацией о молекулах

   Alanine ala A hydrophobic  Lysine lys K charged  

Пример #3 parsemoldb.php — разбирает moldb.xml и помещает данные в массив молекул

class AminoAcid var $name ; // название аминокислоты
var $symbol ; // трехбуквенное обозначение
var $code ; // однобуквенный код
var $type ; // гидрофобная, заряженная, нейтральная

function AminoAcid ( $aa )
foreach ( $aa as $k => $v )
$this -> $k = $aa [ $k ];
>
>

function readDatabase ( $filename )
// чтение XML базы данных аминокислот
$data = implode ( «» , file ( $filename ));
$parser = xml_parser_create ();
xml_parser_set_option ( $parser , XML_OPTION_CASE_FOLDING , 0 );
xml_parser_set_option ( $parser , XML_OPTION_SKIP_WHITE , 1 );
xml_parse_into_struct ( $parser , $data , $values , $tags );
xml_parser_free ( $parser );

// проход через структуры
foreach ( $tags as $key => $val ) if ( $key == «molecule» ) $molranges = $val ;
// каждая смежная пара значений массивов является верхней и
// нижней границей определения молекулы
for ( $i = 0 ; $i < count ( $molranges ); $i += 2 ) $offset = $molranges [ $i ] + 1 ;
$len = $molranges [ $i + 1 ] — $offset ;
$tdb [] = parseMol ( array_slice ( $values , $offset , $len ));
>
> else continue;
>
>
return $tdb ;
>

function parseMol ( $mvalues )
for ( $i = 0 ; $i < count ( $mvalues ); $i ++) $mol [ $mvalues [ $i ][ "tag" ]] = $mvalues [ $i ][ "value" ];
>
return new AminoAcid ( $mol );
>

$db = readDatabase ( «moldb.xml» );
echo «** База данных аминокислот:\n» ;
print_r ( $db );

После выполнения parsemoldb.php переменная $db содержит массив объектов AminoAcid, а вывод соответственно следующий:

** База данных аминокислот: Array ( [0] => aminoacid Object ( [name] => Alanine [symbol] => ala [code] => A [type] => hydrophobic ) [1] => aminoacid Object ( [name] => Lysine [symbol] => lys [code] => K [type] => charged ) )

Источник

How to Convert XML to Array in PHP?

How to Convert XML File to Array in PHP?

In this tutorial, you will learn about how to convert an XML file to Array with PHP. We will parse the XML code into an Array using the PHP functions.

We will use file_get_contents() , simplexml_load_string() , json_encode() and json_decode() functions. These PHP built-in functions will help us to convert the XML file into PHP array.

Create an XML File

XML is an eXtensible Markup Language same as HTML but it does not have predefined tags to use. You can create your own tags relative to values and use them.

XML was designed to store and transport data with self-descriptive tags. It is fully independent to create our own tags corresponding to data needs and then we can store data in XML and search later, and share with others.

So first, we will create an XML file. You can take any such information for example to show in an XML file and store in it. See the following sample XML file, you can copy it for reference.

You can download this file here.

Convert XML File to Array with PHP

Now we will use the above XML file to convert it into an array with PHP functions. It is very simple and easy to do that, you just have to read the file and then convert XML strings into an object.

Then we can parse the XML and convert the XML object into JSON and decode it to print the PHP associative array.

OK. let’s get understand line by line.

XML file path variable

So the first thing you need to do is declare a variable that has the XML file path. The path could be from your machine or online.

Read the XML file

Now we will read the XML file using the file_get_contents() function by giving the parameter referring to the above path variable.

Convert XML string into an object

This is the main step to convert the XML file to an array in PHP. So we will use the simplexml_load_string() PHP function to parse the XML file. It will make an object from the XML string.

Convert XML object to JSON

Now we will use the json_encode() PHP function to convert the XML object into JSON object. Then it will return JSON representation value.

Convert into associative array

This is the final step, in this step, we will use the json_decode() function to decode the JSON data into PHP associative array.

Note: Don’t forget to pass the true value of the second parameter of json_decode. If the value is true then data will return as an associative array and if the value is false then data will be object.

OK. Now you can print the $dataArr variable anywhere using the print_r() function.

See All Code Together

In the above steps, I have explained one by one line about how to convert an XML file or data into a PHP array and how it works.

You can check out the following code same as the above code but all together.

Hope it is helpful for you. Please share it with your friends. If you have any questions about this tutorial or anything please don’t hesitate to ask me. Comment your query I will respond to you as soon as possible.

Источник

Оцените статью