Converting a SimpleXML Object to an Array
I found this in the PHP manual comments:
/**
* function xml2array
*
* This function is part of the PHP manual.
*
* The PHP manual text and comments are covered by the Creative Commons
* Attribution 3.0 License, copyright (c) the PHP Documentation Group
*
* @author k dot antczak at livedata dot pl
* @date 2011-04-22 06:08 UTC
* @link http://www.php.net/manual/en/ref.simplexml.php#103617
* @license http://www.php.net/license/index.php#doc-lic
* @license http://creativecommons.org/licenses/by/3.0/
* @license CC-BY-3.0 <http://spdx.org/licenses/CC-BY-3.0>
*/
function xml2array ( $xmlObject, $out = array () )
{
foreach ( (array) $xmlObject as $index => $node )
$out[$index] = ( is_object ( $node ) ) ? xml2array ( $node ) : $node;
return $out;
}
It could help you. However, if you convert XML to an array you will loose all attributes that might be present, so you cannot go back to XML and get the same XML.
PHP Converting from XML to JSON with a SimpleXML object. Array with items tag causing issues
A generic conversion has no possibility to know that a single element should be an array in JSON.
SimpleXMLElement
properties can be treated as an Iterable to traverse sibling with the same name. They can be treated as an list or a single value.
This allows you to build up your own array/object structure and serialize it to JSON.
$xml = <<<'XML'
<apns>
<item>
<apn>apn1</apn>
</item>
<item>
<apn>apn2</apn>
</item>
</apns>
XML;
$apns = new SimpleXMLElement($xml);
$json = [
'apns' => []
];
foreach ($apns->item as $item) {
$json['apns'][] = ['apn' => (string)$item->apn];
}
echo json_encode($json, JSON_PRETTY_PRINT);
This still allows you to read/convert parts in a general way. Take a more in deep look at the SimpleXMLElement class. Here are method to iterate over all children or to get the name of the current node.
How to convert SimpleXMLObject into PHP Array?
Book Of Zeus code wrapped in function to make it work recursively:
function xml2array($xml)
{
$arr = array();
foreach ($xml as $element)
{
$tag = $element->getName();
$e = get_object_vars($element);
if (!empty($e))
{
$arr[$tag] = $element instanceof SimpleXMLElement ? xml2array($element) : $e;
}
else
{
$arr[$tag] = trim($element);
}
}
return $arr;
}
$xml = new SimpleXMLElement($string);
print_r(xml2array($xml));
Array
(
[id] => 1234
[label] => 118
[username] => root
[password] => helloWorld
[hardware] => Array
(
[memory] => 4GB RAM
[storage_drives] => Array
(
[storage_drive_1] => 2TB SATA 7,200RPM
[storage_drive_2] => 1TB SATA 7,200RPM
[storage_drive_3] => Not Applicable
[storage_drive_4] => Not Applicable
)
)
)
PHP: convert simpleXML object to two-dimensional array
It can be done by iterating over the history elements like so:
$obj = simplexml_load_string($xml); // change to simplexml_load_file if needed
$arr = array();
foreach($obj->history as $history){
$arr[(string)$history->groupName->item] = (int)$history->groupName->groupCount;
}
Outputs
Array
(
[item1] => 53
[item2] => 20
[item3] => 7
[item4] => 4
[item5] => 2
[item6] => 2
[item7] => 1
)
SimpleXMLElement to PHP Array
The $answer
can already work as an array. You can do this if you want put it in a real array,
$array = array();
foreach($answer as $k => $v) {
$array[$k] = $v;
}
Looping through a SimpleXML object, or turning the whole thing into an array
You can use the SimpleXML
object (or its properties) in a foreach
loop. If you want to loop through all the 'records' something like this can be used to access and display the data:
//Loop through all the members of the Item array
//(essentially your two database rows).
foreach($SimpleXML->body->QueryWithAttributesResult->Item as $Item){
//Now you can access the 'row' data using $Item in this case
//two elements, a name and an array of key/value pairs
echo $Item->Name;
//Loop through the attribute array to access the 'fields'.
foreach($Item->Attribute as $Attribute){
//Each attribute has two elements, name and value.
echo $Attribute->Name . ": " . $Attribute->Value;
}
}
Note that $Item will be a SimpleXML object, as is $Attribute, so they need to be referenced as objects, not arrays.
While the example code above is looping through the arrays in the SimpleXML object ($SimpleXML->body->QueryWithAttributesResult->Item), you can also loop through a SimpleXML object (say $SimpleXML->body->QueryWithAttributesResult->Item[0]), and that would give you each of the object's properties.
Each child element of a SimpleXML object is an XML entity. If the XML entity (tag) is not unique, then the element is simply an array of SimpleXML objects representing each entity.
If you want, this should create a more common row/fields array from your SimpleXML object (or get you close):
foreach($SimpleXML->body->QueryWithAttributesResult->Item as $Item){
foreach($Item->Attribute as $Attribute){
$rows[$Item->Name][$Attribute->Name] = $Attribute->Value;
}
}
//Now you have an array that looks like:
$rows['message12413344443260']['active'] = 1;
$rows['message12413344443260']['user'] = 'john';
//etc.
How can i convert array to SimpleXMLElement Object
$xml = '<?xml version='1.0' standalone='yes'?>';
function rekursiveArrayToXML($array, &$xml, $name = 'root') {
$xml .= "$<$name";
if (is_array($array) AND isset($array['@attributes'])) {
foreach ($array['@attributes'] as $k => $v) {
$xml .= " $k=\"$v\"";
}
unset($array['@attributes']);
}
$xml .= ">";
if (is_array($array)) {
foreach ($array as $k => $v) {
rekursiveArrayToXML($v, $xml, $k);
}
} else {
$xml .= $array;
}
$xml .= "</$name>\n";
}
$array = array(
'@attributes' => Array
(
'Id' => 925343664,
'FloorplanID' => 617454,
'BuildingID' => 0
),
'Unit' => Array(),
'Comment' => Array(),
'Availability' => Array
(
'VacancyClass' => 'Occupied',
'MadeReadyDate' => Array
(
'@attributes' => Array
(
'Month' => 1,
'Day' => 24,
'Year' => 2016,
)
)
)
);
rekursiveArrayToXML($array, $xml);
var_export(simplexml_load_string($xml));
something like that ;)
Related Topics
Preserve Key Order (Stable Sort) When Sorting With PHP'S Uasort
Yii2 Htaccess - How to Hide Frontend/Web and Backend/Web Completely
A Problem Occurred Somewhere in the Ssl/Tls Handshake
Serializing PHP Object to Json
How to Linkify Urls in a String With PHP
Why Is This PHP Call to Json_Encode Silently Failing - Inability to Handle Single Quotes
Page Redirect After Certain Time PHP
How to Overload Operators in PHP
Symfony2 - Force File Download
Fatal Error: Cannot Use Object of Type MySQLi_Result
Generating Cryptographically Secure Tokens
What Is the Default Lifetime of a Session
How to Group a Multidimensional Array by a Particular Subarray Value