php dom import simplexml
dom_import_simplexml
dom_import_simplexml — Получает объект класса DOMElement из объекта класса SimpleXMLElement
Описание
Список параметров
Возвращаемые значения
Список изменений
Версия | Описание |
---|---|
8.0.0 | Функция больше не возвращает null в случае возникновения ошибки. |
Примеры
Пример #1 Импорт SimpleXML в DOM с помощью функции dom_import_simplexml()
Смотрите также
User Contributed Notes 5 notes
justinpatrin at php dot net:
> To get a proper DOM document (which you need to do most things) you need.
SimpleXML is an ‘Object Mapping XML API’. It is not DOM, per se. SimpleXML converts the XML elements into PHP’s native data types.
The dom_import_simplexml and simplexml_import_dom functions do *not* create separate copies of the original object. You are free to use the methods of either or both interchangeably, since the underlying instance is the same.
// initialize a simplexml object
$sxe = simplexml_load_string ( ‘ ‘ );
// simplexml adds an attribute on the new element
$element [ ‘creator’ ] = ‘simplexml’ ;
SimpleXMLElement Object
(
[dom_element] => SimpleXMLElement Object
(
[@attributes] => Array
(
[creator] => dom
[sxe_attribute] => added by simplexml
)
[sxe_element] => SimpleXMLElement Object
(
[@attributes] => Array
(
[creator] => simplexml
[dom_attribute] => added by dom
)
What this illustrates is that both interfaces are operating on the same underlying object instance. Also, when you dom_import_simplexml, you can create and add new elements without reference to an ownerDocument (or documentElement).
So passing a SimpleXMLElement to another method does not mean the recipient is limited to using SimpleXML methods.
Hey Presto! Your telescope has become a pair of binoculars!
//No need to initiate, import and append on example#1
(. )
$dom_sxe = dom_import_simplexml($sxe);
if (!$dom_sxe) <
echo ‘Erreur lors de la conversion du XML’;
exit;
>
Very useful to add a CDATA node with SimpleXMLElement (use it like addChild) :
class My_SimpleXMLElement extends SimpleXMLElement <
SimpleXML
User Contributed Notes 31 notes
Three line xml2array:
In reply to soloman at textgrid dot com,
$xml = simplexml_load_string($file);
$array = (array)$xml;
dynamic sql in php using xml:
test.xml:
SELECT * FROM USERS
WHERE >
WHERE username = «%s» ;
This will NOT work
Here is a recursive function that will convert a given SimpleXMLElement object into an array, preserving namespaces and attributes.
Simple means simple. If you know the structure and just want the value of a tag:
I had a problem with simplexml reading nodes from an xml file. It always return an SimpleXML-Object but not the text inside the node.
Optimizing aalaap at gmail dot com’s php
«, while in an PHP array, the key of which must be different.
I think the array structure developed by svdmeer can fit for XML, and fits well.
here is an example array converted from an xml file:
array(
«@tag»=>»name»,
«@attr»=>array(
«id»=>»1″,»class»=>»2»)
«@text»=>»some text»,
)
or if it has childrens, that can be:
Also, I wrote a function that can change that array back to XML.
Here’s a quick way to dump the nodeValues from SimpleXML into an array using the path to each nodeValue as key. The paths are compatible with e.g. DOMXPath. I use this when I need to update values externally (i.e. in code that doesn’t know about the underlying xml). Then I use DOMXPath to find the node containing the original value and update it.
Wrapper XMLReader class, for simple SAX-reading huge xml:
https://github.com/dkrnl/SimpleXMLReader
/**
* Simple XML Reader
*
* @license Public Domain
* @author Dmitry Pyatkov(aka dkrnl)
* @url http://github.com/dkrnl/SimpleXMLReader
*/
class SimpleXMLReader extends XMLReader
<
$xml = new SimpleXMLElement ( » » );
Here are two quick and dirty functions that use SimpleXML to detect if a feed xml is RSS or ATOM:
None of the XML2Array functions that I found satisfied me completely; Their results did not always fit the project I was working on, and I found none that would account for repeating XML elements (such as
)
So I rolled out my own; hope it helps someone.
/**
* Converts a simpleXML element into an array. Preserves attributes.
* You can choose to get your elements either flattened, or stored in a custom
* index that you define.
* For example, for a given element
*
*
*
*
* Repeating fields are stored in indexed arrays. so for a markup such as:
*
*
If you tried to load an XML file with this, but the CDATA parts were not loaded for some reason, is because you should do it this way:
$xml = simplexml_load_file($this->filename, ‘SimpleXMLElement’, LIBXML_NOCDATA);
This converts CDATA to String in the returning object.
// Sherwin R. Terunez
//
// This is my own version of XML Object to Array
//
For example, this does not work:
FAIL! This function works better than the one I posted below:
I know it is over-done, but the following is a super-short example of a XML to Array conversion function (recursive):
Addition to QLeap’s post:
SimpleXML will return a reference to an object containing the node value and you can’t use references in session variables as there is no feasible way to restore a reference to another variable.
Here is an example of an easy mapping between xml and classes defined by user.
if for some reasons you need the string value instead of the simpleXML Object you can cast the return value as a string.
Here’s a function I came up with to convert an associative array to XML. Works for multidimensional arrays as well.
XML data values should not contain «&» and that need to be replaced by html-entity «&»
You can use this code to replace lonely «&» to «&»:
Here is a very robust SimpleXML parser. Can be used to load files, strings, or DOM into SimpleXML, or can be used to perform the reverse when handed SimpleXML.
SimpleXML. Начало работы
Расширение SimpleXML предоставляет очень простой и легкий в использовании набор инструментов для преобразования XML в объект, с которым можно затем работать через его свойства и с помощью итераторов. SimpleXML присутствует в PHP начиная с версии 5.
Для наглядности, в качестве примера будем использовать XML, описывающий простой кулинарный рецепт, взятый с википедии.
Загрузка XML
Прежде чем начать обрабатывать данные, их нужно сначала загрузить. Для этого достаточно использовать функцию simplexml_load_file(). Она принимает имя файла, и возвращает объект типа SimpleXMLElement. И с этим объектом уже можно будет работать.
Кроме того, существует еще и функция simplexml_load_string(), которая берет XML не из файла, а из строки.
Получение данных
SimpleXML предоставляет очень удобный способ получения данных из XML. К примеру, для того чтобы получить какой-либо узел документа достаточно просто обратится к этому узлу по имени:
Для того что бы получить, к примеру, третий ингредиент (теплая вода), достаточно обратиться к нему по индексу:
Шаги приготовления (step) являются дочерними для элемента instructions, чтобы получить их, нужно сначала получить instructions:
Атрибуты
Работать с атрибутами тоже очень легко. Они доступны как ассоциативный массив своего элемента. То есть, для того что бы получить название рецепта (атрибут name корневого узла recipe), достаточно написать:
Или, для получения количества первого ингредиента можно написать так:
Сейчас мы рассмотрели только один способ получения данных: когда нам уже известны названия узлов и атрибутов. Но случается и так, когда структура XML файла заранее не известна, но нам нужно его обработать. SimpleXML предоставляет и такую возможность.
Получение дочерних узлов
то второй ингредиент.
Обойти все дочерние ветви первого уровня легко можно при помощи цикла foreach:
Фукция count() позволяет определить количество дочерних узлов.
Для того, чтобы получить имя текущий ветви, используется метод getName():
Получение атрибутов
Получить список атрибутов для текущего элемента поможет метод attributes(). По функционалу и механизму работы он аналогичен методу children(), за тем исключением, что здесь идет работа с атрибутами.
Изменение значений узлов и атрибутов
Объект SimpleXMLElement позволяет манипулировать всеми элементами:
Добавление элементов и атрибутов
Чтобы добавить дочерний элемент к текущему, достаточно использовать метод addChild(). Первым параметром идет имя нового элемента, вторым значение, которое задавать необязательно.
Добавим еще один шаг к инструкциям:
Метод addAttribute() позволяет добавить атрибут к текущему узлу. Первый параметр это имя атрибута, второй значение.
Использование XPath
SimpleXML включает в себя встроенную поддержку XPath. Поиск всех элементов :
Взаимодействие с DOM
PHP может преобразовывать XML узлы из SimpleXML в формат DOM и наоборот. Этот пример показывает, как можно изменить DOM элемент в SimpleXML:
What’s the difference between PHP’s DOM and SimpleXML extensions?
I’m failing to comprehend why do we need 2 XML parsers in PHP.
Can someone explain the difference between those two?
5 Answers 5
SimpleXml
Both of these are based on libxml and can be influenced to some extend by the libxml functions
But that’s just my 2c. Make up your own mind 🙂
On a sidenote, there is not two parsers, but a couple more in PHP. SimpleXml and DOM are just the two that parse a document into a tree structure. The others are either pull or event based parsers/readers/writers.
Also see my answer to
I’m going to make the shortest answer possible so that beginners can take it away easily. I’m also slightly simplifying things for shortness’ sake. Jump to the end of that answer for the overstated TL;DR version.
DOM and SimpleXML aren’t actually two different parsers. The real parser is libxml2, which is used internally by DOM and SimpleXML. So DOM/SimpleXML are just two ways to use the same parser and they provide ways to convert one object to another.
SimpleXML is intended to be very simple so it has a small set of functions, and it is focused on reading and writing data. That is, you can easily read or write a XML file, you can update some values or remove some nodes (with some limitations!), and that’s it. No fancy manipulation, and you don’t have access to the less common node types. For instance, SimpleXML cannot create a CDATA section although it can read them.
DOM offers a full-fledged implementation of the DOM plus a couple of non-standard methods such as appendXML. If you’re used to manipulate DOM in Javascript, you’ll find exactly the same methods in PHP’s DOM. There’s basically no limitation in what you can do and it evens handles HTML. The flipside to this richness of features is that it is more complex and more verbose than SimpleXML.
Side-note
People often wonder/ask what extension they should use to handle their XML or HTML content. Actually the choice is easy because there isn’t much of a choice to begin with:
As others have pointed out, the DOM and SimpleXML extensions are not strictly «XML parsers», rather they are different interfaces to the structure generated by the underlying libxml2 parser.
The DOM interface, on the other hand, treats XML as a structured document, where the representation used is as important as the data represented. It therefore provides much more granular and explicit access to different types of «node», such as entities and CDATA sections, as well as some which are ignored by SimpleXML, such as comments and processing instructions. It also provides a much richer set of manipulation functions, allowing you to rearrange nodes and choose how to represent text content, for instance. The tradeoff is a fairly complex API, with a large number of classes and methods; since it implements a standard API (originally developed for manipulating HTML in JavaScript), there may be less of a «natural PHP» feel, but some programmers may be familiar with it from other contexts.
Php dom import simplexml
Пример #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.