php create xml file from array
Php create xml file from array
Array2xml is a PHP library that converts array to valid XML.
Usage (Ex.: RSS Last News)
Load the library and set custom configuration:
Start by creating a root element:
Now pass elements from DB query in cycle:
You can also set element attributes individually. The example below appends an attribute AttributeName to item node:
Or, if your node doesn’t have children, you can use this:
This will set both attributes and the content of channel node.
Alternatively, you can use setElementsAttrs() method:
Note that in this case all elements with specified names will have identical attribute names and values.
Finally, convert and print output data to screen
You can easily configure this lib to fit your specific use case using setters described below.
Sets XML version header.
Set XML Root Element Name
Set XML Root Element Attributes
Set Attributes of every XML Elements that matches the given names. Example argument: [‘elementName’ => [‘someAttr’ => ‘attrValue’]]
Marking given elements as CData ones
Marking given elements as raw ones
Set default prefix for numeric nodes
On/Off Skip numeric nodes
In some cases you might want to control the exact syntax of empty elements.
By default, nodes that are empty or equal to null are using self-closing syntax( ).
You can override this behavior using Array2xml::EMPTY_FULL to force using closing tag( ).
Available agruments are Array2xml::EMPTY_SELF_CLOSING or Array2xml::EMPTY_FULL
Remove numbers from element names.
This is a easy workaround to have identically named elements in your XML built from an array.
For example, let’s build an XML with 3 image nodes:
That’s it! Now we have a nasty XML with 3 identically named nodes in it.
Создание XML-документа на PHP
В нижеследующем примере идёт генерация XML-документа на PHP:
Всё самое основное, что Вы должны знать при создании XML-документов через PHP, находится в данном примере. Код я постарался хорошо прокомментировать, поэтому вопросов возникнуть не должно. Вы, обладая данными знаниями, уже можете создать практически любой XML-документ, используя стандарт DOM. А в следующей статье я Вам покажу, как парсить XML-документ через PHP.
Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!
Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.
Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления
Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.
Порекомендуйте эту статью друзьям:
Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):
Комментарии ( 1 ):
Для добавления комментариев надо войти в систему.
Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.
Copyright © 2010-2021 Русаков Михаил Юрьевич. Все права защищены.
Alex’s Blog
I’ve been working with the Google Contacts API lately and needed to construct some XML as a part of that. PHP’s DOMDocument works really great for this, but it can get complicated fast as you need to create lots of variables for all of your elements, children, etc. It can make it quite hard to do dynamically.
An easier method would be to just convert an array into XML, the opposite of simplexml_load_string() if you will. So I wrote some code that does exactly that and I thought I’d share it incase anyone else would find it helpful. 🙂
Start by creating your array of data. I used a numeric array instead of an associative array because you can have duplicate elements in XML while you cannot have duplicate array keys.
An array such as that is easy to dynamically create based on your source data, it’s easy to read, and can be fairly easily manipulated.
name is the only required item of each array and it’s the tag name of the element. attributes is an array of attributes for the element and value is the value. Both of these are optional. Any children arrays are children elements and their structures should be the same.
Now here’s the code I wrote that converts the above array into some XML:
You first create a blank canvas by creating a new instance of the DOMDocument class and then you pass the class instance (needed for creating elements in the correct character set and such) and the data array to the generate_xml_element() function. This function will create the top level element and then recursively call itself on any child elements until it’s gone through the whole array.
Once it’s done, you’ll need to append the element to the DOM using the inherited appendChild() function. Then calling saveXML will give you the XML output. The above example data array will give you something like this (maybe or maybe not nicely formatted with whitespace depending on what mood DOMDocument is in):
And there you have it!
21 thoughts on “ Easily Create XML In PHP Using A Data Array ”
I tried your creating an XML file from a PHP array. I used your example and could not the XML tree, only the values. I am probably missing something. I have been using PHP for over a dozen years, however this is the first time I tried to turn a PHP array in an XML output. If I ask real nice you assist me?
I would like to take this sample array and turn it into a similar XML out as the example below.
With XML, I believe you need to have a single top level element to contain all of your data. Even if you don’t, my code requires one, so I made it “location”.
Now the dumb question of the day; How do I get it to display as an XML tree like yours? I feel like such a novice today.
Mine comes out as one long of only the values;
95610Citrus HeightsKMCCMcClellan Airfield7.306701182156538.667-121.4
If you’re echo ‘ing it, then your browser is probably trying to render it as HTML tags. Use var_dump() or view the source.
Thank you for everything. “View Source” does not seem to work. The var_dump($xml) does not give me that XML format.
Result from var_dump($xml:
string(223) ” 95610Citrus HeightsKMCCMcClellan Airfield7.306701182156538.667-121.4 “
If you wrap the output in htmlentities() you’ll get the response as XML.
add header( “content-type: application/xml; charset=ISO-8859-15” ); in your code
Hi, I need your help.
This way you can print:
?>
—————————————————-
However, only the html table is added to the database, data is not added into HTML table cells.
How do i generate a tree structure like a parent can have a child and that child can be a parent to another child
PHP XML Tutorial: Create, Parse, Read with Example
Updated August 27, 2021
What is XML?
XML is the acronym for Extensible Markup Language.
XML is used to structure, store and transport data from one system to another.
XML is similar to HTML.
It uses opening and closing tags.
Unlike HTML, XML allows users to define their own tags.
In this tutorial, you will learn-
What is DOM?
DOM is the acronym for Document Object Model.
It’s a cross platform and language neutral standard that defines how to access and manipulate data in;
DOM XML is used to access and manipulate XML documents. It views the XML document as a tree-structure.
XML Parsers
An XML parser is a program that translates the XML document into an XML Document Object Model (DOM) Object.
The XML DOM Object can then be manipulated using JavaScript, Python, and PHP etc.
The keyword CDATA which is the acronym for (Unparsed) Character Data is used to ignore special characters such as “ ” when parsing an XML document.
Why use XML?
XML Document example
Let’s suppose that you are developing an application that gets data from a web service in XML format.
Below is the sample of how the XML document looks like.
How to Read XML using PHP
Let’s now write the code that will read the employees XML document and display the results in a web browser. Index.php
Testing our application
Assuming you saved the file index.php in phptus/xml folder, browse to the URL http://localhost/phptuts/xml/index.php
How to Create an XML document using PHP
We will now look at how to create an XML document using PHP.
We will use the example above in the DOM tree diagram.
The following code uses the PHP built in class DOMDocument to create an XML document.
Php create xml file from array
Пример #1 Файл example.php с XML строкой
Таким образом, это язык. Это всё равно язык программирования. Или
это скриптовый язык? Все раскрывается в этом документальном фильме,
похожем на фильм ужасов.
SimpleXML пользоваться очень просто! Попробуйте получить какую-нибудь строку или число из базового XML-документа.
Пример #2 Получение части документа
Результат выполнения данного примера:
В PHP получить доступ к элементу в XML документе, содержащим в названии недопустимые символы (например, дефис), можно путём заключения данного имени элемента в фигурные скобки и апострофы.
Пример #3 Получение строки
Результат выполнения данного примера:
Пример #4 Доступ к неуникальным элементам в SimpleXML
В том случае, если существует несколько экземпляров дочерних элементов в одном родительском элементе, то нужно применять стандартные методы итерации.
Результат выполнения данного примера:
Пример #5 Использование атрибутов
До сих пор мы только получали названия и значения элементов. SimpleXML может также получать доступ к атрибутам элемента. Получить доступ к атрибуту элемента можно так же, как к элементам массива ( array ).
Результат выполнения данного примера:
Пример #6 Сравнение элементов и атрибутов с текстом
Результат выполнения данного примера:
Пример #7 Сравнение двух элементов
Два элемента SimpleXMLElements считаются разными, даже если они указывают на один и тот же объект.
Результат выполнения данного примера:
Пример #8 Использование XPath
‘ // ‘ служит в качестве шаблона. Для указания абсолютного пути, опустите одну из косых черт.
Результат выполнения данного примера:
Пример #9 Установка значений
Данные в SimpleXML не обязательно должны быть неизменяемыми. Объект позволяет манипулировать всеми элементами.
Результат выполнения данного примера:
Пример #10 Добавление элементов и атрибутов
SimpleXML имеет возможность легко добавлять дочерние элементы и атрибуты.
Результат выполнения данного примера:
Пример #11 Взаимодействие с DOM
PHP может преобразовывать XML-узлы из SimpleXML в формат DOM и наоборот. Этот пример показывает, как можно изменить DOM-элемент в SimpleXML.
Результат выполнения данного примера:
User Contributed Notes 15 notes
There is a common «trick» often proposed to convert a SimpleXML object to an array, by running it through json_encode() and then json_decode(). I’d like to explain why this is a bad idea.
Additionally, because it is not designed for this purpose, the conversion to JSON and back will actually lose information in some situations. For instance, any elements or attributes in a namespace will simply be discarded, and any text content will be discarded if an element also has children or attributes. Sometimes, this won’t matter, but if you get in the habit of converting everything to arrays, it’s going to sting you eventually.
Of course, you could write a smarter conversion, which didn’t have these limitations, but at that point, you are getting no value out of SimpleXML at all, and should just use the lower level XML Parser functions, or the XMLReader class, to create your structure. You still won’t have the extra convenience functionality of SimpleXML, but that’s your loss.