php simplexmlelement to array

PHP SimpleXml Elements to Array

I need to send a string of html has is like content somecode morecode more code

This would go into an array like :

But I’m not figuring out how to transform this data to the array.

5 Answers 5

However this is assuming the sample given is an exact representation of your XML (i.e. you use > and

php simplexmlelement to array. Смотреть фото php simplexmlelement to array. Смотреть картинку php simplexmlelement to array. Картинка про php simplexmlelement to array. Фото php simplexmlelement to array

What exactly are you trying to do? If you give a broader picture of the problem you are trying to solve we might be able to give a better solution.

So you want to convert this tree data structure:

Into some sort of flat array:

would be tricky. This is a classic CS problem that doesn’t have a lot of good answerers. The tree structure provides information on the relationships between entries that a flat array or list does not. Any attempt to flatten the tree into a list will loose that referential context.

You could either explode the string and then walk through it keeping track of parent elements or ignoring them (see tag2). If I had to do something with the xml I would drop it in a SimpleXMLElement, which would produce something like this:

With this I can walk it with foreach and find out the tag and it’s contents. I can test to see if the contents are strings or child elements and if so walk them. A recursive function would make fairly short work of this problem. The biggest issue is how to represent the data once it flattens.

If you flatten it into the array example I provided earlier the parent and child tags loose any implied relationship to each other. If this isn’t a problem, great. Write the recursive function and you are done. Here is some psudocode:

However if you need to somehow keep those relationships intact you have a bit of a problem and will need to devise some sort of scheme for that

Источник

Convert simplexml object to array in php

One of the most handy functions of this extension is simplexml_load_string. Here is an example :

Nothing special over there. But one thing that many developers try to do is convert the above object into an array for easy looping over a foreach somewhere in their code.

You can attempt this in many ways. Look at the php documentation page and many people have commented with their version of code to convert a simplexml object to an array.

Here is a common trick :

Those 2 json functions are smart enough to convert a simplexml object to an array recursively. The output might be :

But the above approach has a problem. Have a closer look :

The above code has 2 xml strings. One has a single row element and another has 2 of them. And the output as you can guess is :

then it would work in the 2nd case but fail in the first one.

You may want to try an alternate function like :

But the result is same :

The problem with the above methods is that they all are looping over the simplexml object as if it was an array. This approach may not work well. The simplexmlelement class provides a method called children() which provides the children of an element.

Use the children method

to be used like this :

Few notable points in the latest method is :

9 thoughts on “ Convert simplexml object to array in php ”

All the code in this post has been htmlentitied()

Works perfectly, thanks.
$t = array(); // I think you can remove this line in xml2array() method.

This “tiny” great solution save me a lot of codification hours.

Really helpful to me this content
Thank you so much

Hi, I’m currently using your code in a new PHP script to generate KML (Googlemap, googleearth, openstreetmap) based on ical from GoogleCalendar.
I plan to deliver it using GNU LGLP license

yes but this is not for large xml files over 200k lines. You will get an empty json_decode result

Thank you! Very helpful.

This just savedme after pulling at my hair for quite a whhile.
thanks so much.

Little “fast” fix to fix:

function xml2array($xml) <
$arr = array();

if (count($r->children()) == 0) <
if($xml->$k->count() == 1) <
$arr[$r->getName()] = strval($r);
>else <
$arr[$r->getName()][] = strval($r);
>//Endif
> else <

$arr[$r->getName()][] = xml2array($r);
>//Endif
>//Endofreach

Источник

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.

Источник

jasondmoss / simpleXmlToArray.php

This comment has been minimized.

Copy link Quote reply

ncovercash commented Jul 5, 2017

Thanks for having this when even stack overflow couldn’t help, saved me quite a headache

This comment has been minimized.

Copy link Quote reply

samuelwilliams commented Sep 17, 2018

This comment has been minimized.

Copy link Quote reply

samjross commented Feb 14, 2020

is_array($node) returned false for me, so it only gave me results one layer down

This comment has been minimized.

Copy link Quote reply

nabaasa commented Jun 14, 2020

This comment has been minimized.

Copy link Quote reply

feldsam commented Sep 13, 2020

The enhanced version, with recursive children

This comment has been minimized.

Copy link Quote reply

MarcelloDM commented Sep 18, 2020 •

In few cases, an XML object can be in a form as showed below:

In this case, the good enhanced function simpleXmlToArray() proposed by @feldsam transforms the XML in an array nesting all the sameParentNode’s sons but it’s not able to convert the recursive SimpleXMLElement because of getting an absent node name. This causes it pushes in the array just last recursiveSon node, overwriting all the others previous.

So, I propose a new version with an if condition on recursive nodes that keeps the not-associative nodes in the transfomed array:

This comment has been minimized.

Copy link Quote reply

roland-d commented Dec 28, 2020

Thanks everybody for chipping in here. I have taken the version from @MarcelloDM and added attributes support and nested nodes are not always added under a numeric value but directly under it’s parent name.

Источник

SimpleXMLElement::attributes

SimpleXMLElement::attributes — Identifies an element’s attributes

Description

This function provides the attributes and values defined within an xml tag.

Note: SimpleXML has made a rule of adding iterative properties to most methods. They cannot be viewed using var_dump() or anything else which can examine objects.

Parameters

An optional namespace for the retrieved attributes

Default to false

Return Values

Returns a SimpleXMLElement object that can be iterated over to loop through the attributes on the tag.

Returns null if called on a SimpleXMLElement object that already represents an attribute and not a tag.

Examples

Example #1 Interpret an XML string

The above example will output:

See Also

User Contributed Notes 15 notes

It is really simple to access attributes using array form. However, you must convert them to strings or ints if you plan on passing the values to functions.

(
[@ attributes ] => Array
(
[ id ] => 55555
)

[ text ] => «hello world»
)
?>

Then using a function

Note that you must provide the namespace if you want to access an attribute of a non-default namespace:

Consider the following example:

Tip to get a real array of all attributes of a node (not SimpleXML’s object acting like an array)

Easiest and safest way to get attributes as an array is to use the iterator_to_array function (see http://php.net/manual/en/function.iterator-to-array.php):

This apparently reads the element as an array and just returns the value of the first property, whether it be the attributes or the value. As seen in the third example, this is unreliable, especially if you’re parsing XML from an outside source that may or may not have attributes on an element that you want the value of.

I certainly do NOT advise anyone to use this since it is undocumented and it is just a coincidence that it works, so it might break in the future without prior notice.

Use attributes to display when it meets certain condition defined attribute / value in xml tags.

Use atributos para exibir quando atende determinada condição definida atributo / valor em tags XML.

Consider the following example:
Considere o seguinte exemplo:

Checks if the attribute value equals «Language», if equal prints everything that is related to «Language».

Verifica se o valor do atributo é igual a «Language», se for, imprime tudo o que for relativo ao mesmo.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *