PHP Parse Xml String

php parse xml string

Try with simple XML, here's an example:

do.php:

<?php
$xml_str = file_get_contents('xmlfile.xml');
$xml = new SimpleXMLElement($xml_str);
$items = $xml->xpath('*/item');

foreach($items as $item) {
echo $item['title'], ': ', $item['description'], "\n";
}

xmlfile.xml:

<?xml version="1.0" encoding="UTF-8"?>
<xml>
<items>
<item title="Hello World" description="Hellowing the world.." />
<item title="Hello People" description="greeting people.." />
</items>
</xml>

How to parse a XML string as document object(DOM) in php

DOMDocument::load — Load XML from a file

As you can see in php manual, load() method only work for loading XML from a file.

If you want to load from string, use DOMDocument::loadXML that load XML from string.

Trying to Parse XML String from HTTP Request in PHP

It expects a file-path or URL, not file-content (because the 3rd parameter is true, while the default is false).

Try removing the 3rd parameter like:

$xml = new SimpleXMLElement($data, 0);

But if that does not work you still have the option:

$xml = simplexml_load_string($data);

// do something with $xml

Parsing XML with simplexml_load_string in PHP

You can simply iterate the SimpleXMLElement objects by accessing the children with -> operator:

$xml = <<<'XML'
<info>
<form tableid="1">
<town_id>
<option value="5102">Moscow</option>
<option value="2587">London</option>
<option value="717">Madrid</option>
<option value="2513">Paris</option>
<option value="5071">Berlin</option>
</town_id>
<town_id>
<option value="9343">XTown</option>
</town_id>
</form>
</info>
XML;

$items = simplexml_load_string($xml);

foreach ($items as $form) {
foreach ($form->town_id as $town) {
foreach ($town->option as $option) {
$attr = $option->attributes();
printf("#%d - %s\n", $attr['value'], $option);
}
}
}

Output

#5102 - Moscow
#2587 - London
#717 - Madrid
#2513 - Paris
#5071 - Berlin
#9343 - XTown

XPath

Alternatively, use xpath method:

$options = $items->xpath('form/town_id/option');
foreach ($options as $option) {
$attr = $option->attributes();
printf("#%d - %s\n", $attr['value'], $option);
}

In this example I used an XPath expression relative to $items (root element, in particular). Adjust the XPath according to your needs. For example, you can fetch all options in the document with //option. Or you might even want to iterate all elements under form having option children:

$containers = $items->xpath('form/*[option]');
foreach ($containers as $c) {
switch ($c->getName()) {
case 'town_id': $label = 'Towns'; break;
case 'country_id': $label = 'Countries'; break;
default:
// Skipping unknown element name
continue;
}

printf("\n%s\n======\n", $label);
foreach ($c->option as $option) {
$attr = $option->attributes();
printf("#%d - %s\n", $attr['value'], $option);
}
}

Sample Output

Towns
======
#5102 - Moscow
#2587 - London
#717 - Madrid
#2513 - Paris
#5071 - Berlin

Towns
======
#9343 - XTown

Countries
======
#3456 - Russia
#4566 - China

convert string to xml in PHP

The contents of the "string" element is an XML document itself - stored in an text node. You can consider it an envelope. So you have to load the outer XML document first and read the text content, then load it as an XML document again.

$outerXML = <<<'XML'
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://www.cebroker.com/CEBrokerWebService/"><licensees><licensee
valid="true" State="FL" licensee_profession="RN"
licensee_number="2676612" state_license_format="" first_name="HENRY"
last_name="GEITER" ErrorCode="" Message="" TimeStamp="2/19/2022
4:53:35 AM" /></licensees></string>
XML;

$envelope = new SimpleXMLElement($outerXML);
$licensees = new SimpleXMLElement((string)$envelope);

echo $licensees->asXML();

In DOM:

$envelope = new DOMDocument();
$envelope->loadXML($outerXML);
$document = new DOMDocument();
$document->loadXML($envelope->documentElement->textContent);

echo $document->saveXML();

How to read XML Child Node Value in a String using PHP?

Use simplexml_load_string() that is for reading xml from string. Then loop through row elements and in loop, loop through FL elements and then get text content and attribute of element.

$xml = simplexml_load_string($string); 
foreach ($xml->Leads->row as $row) {
foreach ($row->FL as $fl) {
echo "{$fl} => {$fl['val']}<br>";
}
}

Cannot parse XML using simplexml_load_string

Method 1.

You can try the below code snippet to parse it an array

$p = xml_parser_create();
xml_parse_into_struct($p, $xml, $values, $indexes);// $xml containing the XML
xml_parser_free($p);
echo "Index array\n";
print_r($indexes);
echo "\nVals array\n";
print_r($values);

Method 2.

function XMLtoArray($xml) {
$previous_value = libxml_use_internal_errors(true);
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->preserveWhiteSpace = false;
$dom->loadXml($xml);
libxml_use_internal_errors($previous_value);
if (libxml_get_errors()) {
return [];
}
return DOMtoArray($dom);
}
function DOMtoArray($root) {
$result = array();
if ($root->hasAttributes()) {
$attrs = $root->attributes;
foreach ($attrs as $attr) {
$result['@attributes'][$attr->name] = $attr->value;
}
}
if ($root->hasChildNodes()) {
$children = $root->childNodes;
if ($children->length == 1) {
$child = $children->item(0);
if (in_array($child->nodeType,[XML_TEXT_NODE,XML_CDATA_SECTION_NODE]))
{
$result['_value'] = $child->nodeValue;
return count($result) == 1
? $result['_value']
: $result;
}
}
$groups = array();
foreach ($children as $child) {
if (!isset($result[$child->nodeName])) {
$result[$child->nodeName] = DOMtoArray($child);
} else {
if (!isset($groups[$child->nodeName])) {
$result[$child->nodeName] = array($result[$child->nodeName]);
$groups[$child->nodeName] = 1;
}
$result[$child->nodeName][] = DOMtoArray($child);
}
}
}
return $result;
}

You can get an array using print_r(XMLtoArray($xml));



Related Topics



Leave a reply



Submit