- PHP simplexml_load_string() Function
- Syntax
- Parameters
- Return Values
- PHP Version
- Example
- Example
- Example
- Example
- SimpleXML. Начало работы
- Загрузка XML
- Получение данных
- Атрибуты
- Получение дочерних узлов
- Получение атрибутов
- Изменение значений узлов и атрибутов
- Добавление элементов и атрибутов
- Использование XPath
- Взаимодействие с DOM
- PHP simplexml_load_string() Function
- Definition and Usage
- Syntax
- Parameter Values
- Technical Details
- More Examples
- Example
- Example
PHP simplexml_load_string() Function
XML is a mark-up language to share the data across the web, XML is for both human read-able and machine read-able. The simple XML parser is used to parse Name, attributes and textual content.
The simplexml_load_string() accepts an (well-formed) XML string as a parameter converts it into an object of the SimpleXMLElement class and returns it.
Syntax
simplexml_load_string($data, [$class_name, $options, $ns, $is_prefix]);
Parameters
This is a string value representing a XML string which is to be interpreted as an object.
This is a string value to representing the name of the class (sub class of the SimpleXMLElement).
If you pass this value, the given XML string is returned as the object of the specified class.
This is an integer value used to specify the additional Libxml parameters.
This is a string value representing the namespace prefix or URI.
This is a boolean value representing whether the previous option is a prefix or an URI.
Return Values
This function returns an object of the SimpleXMLElement class in case of success and returns the boolean value FALSE in case of failure.
PHP Version
This function was first introduced in PHP Version 5 and works in all the later versions.
Example
Following example demonstrates the usage of the simplexml_load_string() function.
"; $xml = simplexml_load_string($data); print_r($xml); ?> Raju 25 2000
This will produce following result −
SimpleXMLElement Object ( [Name] => Raju [Age] => 25 [Salary] => 2000 )
Example
Following is another example of this function, in here we are trying to interpret an XML sting which has multiple records −
"; $xml = simplexml_load_string($str); print(" JavaFX 535 Krishna 11 CoffeeScript 235 Kasyap 2.5.1
"); foreach($xml->children() as $tut) < print($tut->Name ."
"); print($tut->Pages ."
"); print($tut->Author ."
"); print($tut->Version ."
"); print("
"); > ?>
This will produce the following output −
JavaFX 535 Krishna 11 CoffeeScript 235 Kasyap 2.5.1
Example
Following example demonstrates the usage of this method with options −
JavaFX 535 Krishna 11 "; $xml = simplexml_load_string($str, "SimpleXMLElement", LIBXML_BIGLINES, FALSE); print("
"); print($xml->Name ."
"); print($xml->Pages ."
"); print($xml->Author ."
"); print($xml->Version); ?>
This will produce following result −
Example
Gopal CEO Reminder Don't forget to send a file to me XML; $xml = simplexml_load_string($note); echo $xml->to . "
"; echo $xml->from . "
"; echo $xml->heading . "
"; echo $xml->body; ?>
This will produce following result −
Gopal CEO Reminder Don't forget to send a file to me
SimpleXML. Начало работы
Расширение SimpleXML предоставляет очень простой и легкий в использовании набор инструментов для преобразования XML в объект, с которым можно затем работать через его свойства и с помощью итераторов. SimpleXML присутствует в PHP начиная с версии 5.
Для наглядности, в качестве примера будем использовать XML, описывающий простой кулинарный рецепт, взятый с википедии.
Мука Дрожжи Тёплая вода Соль Смешать все ингредиенты и тщательно замесить. Закрыть тканью и оставить на один час в тёплом помещении. Замесить ещё раз, положить на противень и поставить в духовку.
Загрузка XML
Прежде чем начать обрабатывать данные, их нужно сначала загрузить. Для этого достаточно использовать функцию simplexml_load_file(). Она принимает имя файла, и возвращает объект типа SimpleXMLElement. И с этим объектом уже можно будет работать.
$xml = simplexml_load_file('recipe.xml'); print_r($xml);
SimpleXMLElement Object ( [@attributes] => Array ( [name] => хлеб [preptime] => 5 [cooktime] => 180 ) [title] => Простой хлеб [ingredient] => Array ( [0] => Мука [1] => Дрожжи [2] => Тёплая вода [3] => Соль ) [instructions] => SimpleXMLElement Object ( [step] => Array ( [0] => Смешать все ингредиенты и тщательно замесить. [1] => Закрыть тканью и оставить на один час в тёплом помещении. [2] => Замесить ещё раз, положить на противень и поставить в духовку. ) ) )
Кроме того, существует еще и функция simplexml_load_string(), которая берет XML не из файла, а из строки.
$str = file_get_contents('recipe.xml'); $xml = simplexml_load_string($str);
Получение данных
SimpleXML предоставляет очень удобный способ получения данных из XML. К примеру, для того чтобы получить какой-либо узел документа достаточно просто обратится к этому узлу по имени:
// Выводит содержимое элемента echo $xml->title;
Поскольку ингредиентов у нас несколько, то $xml->ingredient будет массивом из четырех элементов. Перебрать все ингредиенты можно так:
foreach ( $xml->ingredient as $ingredient ) echo $ingredient . '
'; >
Для того что бы получить, к примеру, третий ингредиент (теплая вода), достаточно обратиться к нему по индексу:
$xml->ingredient[2]; // элементы массивы нумеруются с нуля
Шаги приготовления (step) являются дочерними для элемента instructions, чтобы получить их, нужно сначала получить instructions:
echo $xml->instructions->step; // выводит текст первого шага
Атрибуты
Работать с атрибутами тоже очень легко. Они доступны как ассоциативный массив своего элемента. То есть, для того что бы получить название рецепта (атрибут name корневого узла recipe), достаточно написать:
Или, для получения количества первого ингредиента можно написать так:
Сейчас мы рассмотрели только один способ получения данных: когда нам уже известны названия узлов и атрибутов. Но случается и так, когда структура XML файла заранее не известна, но нам нужно его обработать. SimpleXML предоставляет и такую возможность.
Получение дочерних узлов
Метод children() возвращает список дочерних элементов. В нашем случае $xml — корневая ветвь, и если написать:
$nodes = $xml->children(); echo $nodes[0];
то получим содержимое элемента , а если:
$nodes = $xml->children(); echo $nodes[2];
Обойти все дочерние ветви первого уровня легко можно при помощи цикла foreach:
Простой хлеб Мука Дрожжи Тёплая вода Соль
Фукция count() позволяет определить количество дочерних узлов.
Для того, чтобы получить имя текущий ветви, используется метод getName():
$nodes = $xml->children(); echo $nodes[0]->getName(); // выведет title
Получение атрибутов
Получить список атрибутов для текущего элемента поможет метод attributes(). По функционалу и механизму работы он аналогичен методу children(), за тем исключением, что здесь идет работа с атрибутами.
$nodes = $xml->children(); // все атрибуты узлаМука foreach ( $nodes[1]->attributes() as $name => $value ) echo 'атрибут ' . $name . ', значение ' . $value . '
'; >
атрибут amount, значение 3
атрибут unit, значение стакан
Изменение значений узлов и атрибутов
Объект SimpleXMLElement позволяет манипулировать всеми элементами:
$xml = simplexml_load_file('recipe.xml'); $xml->title = 'Ржаной хлеб'; $xml->ingredient[0] = 'Ржаная мука'; print_r($xml); $xml->ingredient[2]['amount'] = '300'; $xml->ingredient[2]['unit'] = 'грамм'; print_r($xml->ingredient[2]);
SimpleXMLElement Object ( [@attributes] => Array ( [name] => хлеб [preptime] => 5 [cooktime] => 180 ) [title] => Ржаной хлеб [ingredient] => Array ( [0] => Ржаная мука [1] => Дрожжи [2] => Тёплая вода [3] => Соль ) [instructions] => SimpleXMLElement Object ( [step] => Array ( [0] => Смешать все ингредиенты и тщательно замесить. [1] => Закрыть тканью и оставить на один час в тёплом помещении. [2] => Замесить ещё раз, положить на противень и поставить в духовку. ) ) )
SimpleXMLElement Object ( [@attributes] => Array ( [amount] => 300 [unit] => грамм ) [0] => Тёплая вода )
Добавление элементов и атрибутов
Чтобы добавить дочерний элемент к текущему, достаточно использовать метод addChild(). Первым параметром идет имя нового элемента, вторым значение, которое задавать необязательно.
Добавим еще один шаг к инструкциям:
$node = $xml->instructions; // получаем ветвь инструкций $node->addChild('step', 'Почитать газету'); // добавляем элемент print_r($node);
SimpleXMLElement Object ( [step] => Array ( [0] => Смешать все ингредиенты и тщательно замесить. [1] => Закрыть тканью и оставить на один час в тёплом помещении. [2] => Замесить ещё раз, положить на противень и поставить в духовку. [3] => Почитать газету ) )
Метод addAttribute() позволяет добавить атрибут к текущему узлу. Первый параметр это имя атрибута, второй значение.
$node = $xml->instructions; // получаем ветвь инструкций $step = $node->addChild('step', 'Почитать газету'); // добавляем элемент $step->addAttribute('newspaper', 'Аргументы и факты'); // добавляем артибут print_r($step);
SimpleXMLElement Object ( [@attributes] => Array ( [newspaper] => Аргументы и факты ) [0] => Почитать газету )
Использование XPath
SimpleXML включает в себя встроенную поддержку XPath. Поиск всех элементов :
foreach ($xml->xpath('//step') as $step) echo $step . '
'; >
Смешать все ингредиенты и тщательно замесить.
Закрыть тканью и оставить на один час в тёплом помещении.
Замесить ещё раз, положить на противень и поставить в духовку.
Взаимодействие с DOM
PHP может преобразовывать XML узлы из SimpleXML в формат DOM и наоборот. Этот пример показывает, как можно изменить DOM элемент в SimpleXML:
$dom = new DOMDocument('1.0', 'utf-8'); $dom->load('recipe.xml'); $xml = simplexml_import_dom($dom);
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
- 1С:Предприятие (31)
- API (29)
- Bash (43)
- CLI (99)
- CMS (139)
- CSS (50)
- Frontend (75)
- HTML (66)
- JavaScript (150)
- Laravel (72)
- Linux (146)
- MySQL (76)
- PHP (125)
- React.js (66)
- SSH (27)
- Ubuntu (68)
- Web-разработка (509)
- WordPress (73)
- Yii2 (69)
- БазаДанных (95)
- Битрикс (66)
- Блог (29)
- Верстка (43)
- ИнтернетМагаз… (84)
- КаталогТоваров (87)
- Класс (30)
- Клиент (27)
- Ключ (28)
- Команда (68)
- Компонент (60)
- Конфигурация (62)
- Корзина (32)
- ЛокальнаяСеть (28)
- Модуль (34)
- Навигация (31)
- Настройка (140)
- ПанельУправле… (29)
- Плагин (33)
- Пользователь (26)
- Практика (99)
- Сервер (74)
- Событие (27)
- Теория (105)
- Установка (66)
- Файл (47)
- Форма (58)
- Фреймворк (192)
- Функция (36)
- ШаблонСайта (68)
PHP simplexml_load_string() Function
Convert an XML string into an object, then output keys and elements of the object:
Definition and Usage
The simplexml_load_string() function converts a well-formed XML string into an object.
Syntax
Parameter Values
Parameter | Description |
---|---|
data | Required. Specifies a well-formed XML string |
class | Optional. Specifies the class of the new object |
options | Optional. Specifies additional Libxml parameters. Is set by specifying the option and 1 or 0 (TRUE or FALSE, e.g. LIBXML_NOBLANKS(1)) |
- LIBXML_COMPACT — Activate nodes allocation optimization (may speed up application)
- LIBXML_DTDATTR — Set default DTD attributes
- LIBXML_DTDLOAD — Load external subset
- LIBXML_DTDVALID — Validate with the DTD
- LIBXML_NOBLANKS — Remove blank nodes
- LIBXML_NOCDATA — Merge CDATA as text nodes
- LIBXML_NOEMPTYTAG — Expand empty tags (e.g.
to ), only available in the DOMDocument->save() and DOMDocument->saveXML() functions - LIBXML_NOENT — Substitute entities
- LIBXML_NOERROR — Do not show error reports
- LIBXML_NONET — Disable network access while loading documents
- LIBXML_NOWARNING — Do not show warning reports
- LIBXML_NOXMLDECL — Drop the XML declaration when saving a document
- LIBXML_NSCLEAN — Remove redundant namespace declarations
- LIBXML_PARSEHUGE — Sets XML_PARSE_HUGE flag, which relaxes any hardcoded limit from the parser. This affects limits like maximum depth of a document and limits of the size of text nodes
- LIBXML_XINCLUDE — Implement XInclude substitution
- LIBXML_ERR_ERROR — Get recoverable errors
- LIBXML_ERR_FATAL — Get fatal errors
- LIBXML_ERR_NONE — Get no errors
- LIBXML_ERR_WARNING — Get simple warnings
- LIBXML_VERSION — Get libxml version (e.g. 20605 or 20617)
- LIBXML_DOTTED_VERSION — Get dotted libxml version (e.g. 2.6.5 or 2.6.17)
Technical Details
More Examples
Example
Output the data from each element in the XML string:
$xml=simplexml_load_string($note);
echo $xml->to . «
«;
echo $xml->from . «
«;
echo $xml->heading . «
«;
echo $xml->body;
?>
Example
Output the element’s name and data for each child node in the XML string:
foreach($xml->children() as $child)
echo $child->getName() . «: » . $child . «
«;
>
?>