Php simplexml в массив

php simpleXMLElement to array: null value

I want to have it as an array variable. Therefore I read it with $xml = simplexml_load_file() . The simplest way to convert simpleXMLElement to an associative array I know is to grind it with: json_decode(json_encode((array) $xml),1); The problem is that I don’t want to get the email key as an empty array, but rather as a NULL value. As SimpleXMLElement, it looks like:

public 'email' => object(SimpleXMLElement)[205] 

The only way to achieve this I thought of is iterate through all elements and replace empty array with null value. The problem is that my XML is way bigger (above is just to explain the problem) and I’d have to iterate a lot of XML elements (and this would be manual work — I’m looking for something automatic). Maybe I’m missing some options in one of the functions. or maybe there’s another trick to do this?

@hek2mgl — Ah Ok, I assumed it would :(. Ok, another idea. Load the XML into a string, use some regex to strip out the tags that don’t have values and then parse it. If they are not there, you can treat them as null.

@webnoob Will get messy when the xml grows. also you’ll have to change the regex for each xml format. I’m currently thinking about a SAX parser. This would save the OP from foreach loops in php. The looping would be done in C code of the extension. Also it should be faster than the json_decode/json_encode approach

Читайте также:  Serialize html to json

Hmm, good points. Although, I have to ask the question to the OP on why null value is so important. Why not check for «» . Could even have a helper function to do it for you .

3 Answers 3

I cannot add a comment, but I think this will work for you, it should be faster then a regex or a loop:

//after you json_encode, before you decode $str = str_replace(':[]',':null',json_encode($array)); 

An empty array in JSON is represented by » [] «. Sometimes the arrays are parsed as objects, in that case (or as a fallback) you can replace » :<> » too.

So the overall result of what I want would be: json_decode(str_replace(‘:[]’,’:null’,json_encode($array))) — sounds like a good idea

An empty SimpleXMLElement object will be casted to an empty array. You can change this by by extending from SimpleXMLElement and implementing the JsonSerializable interface and casting an it to null.

/** * Class JsonXMLElement */ class JsonXMLElement extends SimpleXMLElement implements JsonSerializable < /** * Specify data which should be serialized to JSON * * @return mixed data which can be serialized by json_encode. */ public function jsonSerialize() < $array = array(); // json encode attributes if any. if ($attributes = $this->attributes()) < $array['@attributes'] = iterator_to_array($attributes); >// json encode child elements if any. group on duplicate names as an array. foreach ($this as $name => $element) < if (isset($array[$name])) < if (!is_array($array[$name])) < $array[$name] = [$array[$name]]; >$array[$name][] = $element; > else < $array[$name] = $element; >> // json encode non-whitespace element simplexml text values. $text = trim($this); if (strlen($text)) < if ($array) < $array['@text'] = $text; >else < $array = $text; >> // return empty elements as NULL (self-closing or empty tags) if (!$array) < $array = NULL; >return $array; > > 

Then tell simplexml_load_string to return an object of JsonXMLElement class

$xml = 123 ACTIVE  XML; $obj = simplexml_load_string($xml, 'JsonXMLElement'); // print_r($obj); print json_encode($obj, true); /* * Output. < "id": 123, "email": null, "status": "ACTIVE" >*/ 

Источник

Parse XML to an Array in PHP With SimpleXML

Sajal Soni

Sajal Soni Last updated Aug 12, 2020

In this post, you’ll learn how to parse XML into an array in PHP. SimpleXML is a PHP extension that makes this possible.

In your day-to-day PHP development, sometimes you’ll need to deal with XML content. Whether it’s exporting data as XML documents or processing incoming XML documents in your application, it’s always handy to have a library that can perform these operations smoothly. When it comes to dealing with XML in PHP, there are different methods to choose from. In fact, there are different extensions available in PHP that allow you to read and parse XML documents.

PHP’s XML parser is based on James Clark’s expat library, which is a stream-oriented XML library written in C. This XML parser library allows you to parse XML documents, but it’s not able to validate them. It’s event-based and stream-oriented, and thus it’s really useful when you’re dealing with very large XML files—but a little more complicated than it needs to be for small files.

The other option is the SimpleXML extension, which is one of the most popular extensions used by the PHP community to process XML documents. The SimpleXML extension allows you to parse XML documents very easily, just as if you were reading a file in PHP.

In this article, we’re going to use the SimpleXML extension to demonstrate how you could convert XML content into an array. If you want to follow along with the example in this article, make sure that you’ve installed the SimpleXML extension in your PHP installation.

The SimpleXML PHP Extension

The SimpleXML PHP extension provides a complete toolset which you can use to read, write and parse XML documents in your PHP applications. It’s important to note that the SimpleXML extension requires PHP 5 at a minimum. Also, it requires the libxml PHP extension.

The SimpleXML extension is enabled by default, but if you want to check if it’s enabled in your PHP installation, you can check it quickly by using the phpinfo() function.

The phpinfo Function

As you can see, you should see the SimpleXML section in the output of the phpinfo() function.

The SimpleXML extension provides different functions that you could use to read and parse XML content.

Loading an XML String or File With SimpleXML

For example, if you want to parse the XML file, you can use the simplexml_load_file() function. The simplexml_load_file() function allows you to read and parse the XML file in a single call. On the other hand, if you have an XML string which you want to convert into an XML document object, you can use the simplexml_load_string() function.

You could also use the file_get_contents() function to read the file contents and pass the resulting string to the simplexml_load_string() function, which eventually parses it into an object. Alternatively, if you prefer the object-oriented way, you could also use the SimpleXMLElement class and its utility methods to convert an XML string into an object.

In this article, we’re going to use the simplexml_load_file() function to read an XML file, and we’ll see how to convert it into an array. Next, we’ll go through a real-world example to demonstrate how to do this.

How to Convert XML to an Array With PHP

In this section, we’ll see how you can convert XML content into an array.

First of all, let’s quickly go through the steps that you need to follow to convert XML content into an array with the help of the SimpleXML extension.

  • Read the file contents and parse them. At the end of this step, the content is parsed and converted into the SimpleXMLElement object format. We’re going to use the simplexml_load_file() function to achieve this.
  • Next, you need to convert the SimpleXMLElement object into a JSON representation by using the json_encode() function.
  • Finally, you need to use the json_decode() function to decode the JSON content so that it eventually generates an array of all documents.

For demonstration purposes, let’s assume that we have an XML file as shown in the following snippet. We’ll call it employees.xml. It contains the basic details of all employees. Our aim is to convert it into an array that you could use for further processing.

Источник

Looping through a SimpleXML object, or turning the whole thing into an array

I’m trying to work out how to iterate though a returned SimpleXML object. I’m using a toolkit called Tarzan AWS, which connects to Amazon Web Services (SimpleDB, S3, EC2, etc). I’m specifically using SimpleDB. I can put data into the Amazon SimpleDB service, and I can get it back. I just don’t know how to handle the SimpleXML object that is returned. The Tarzan AWS documentation says this:

Look at the response to navigate through the headers and body of the response. Note that this is an object, not an array, and that the body is a SimpleXML object.

[body] => SimpleXMLElement Object ( [QueryWithAttributesResult] => SimpleXMLElement Object ( [Item] => Array ( [0] => SimpleXMLElement Object ( [Name] => message12413344443260 [Attribute] => Array ( [0] => SimpleXMLElement Object ( [Name] => active [Value] => 1 ) [1] => SimpleXMLElement Object ( [Name] => user [Value] => john ) [2] => SimpleXMLElement Object ( [Name] => message [Value] => This is a message. ) [3] => SimpleXMLElement Object ( [Name] => time [Value] => 1241334444 ) [4] => SimpleXMLElement Object ( [Name] => id [Value] => 12413344443260 ) [5] => SimpleXMLElement Object ( [Name] => ip [Value] => 10.10.10.1 ) ) ) [1] => SimpleXMLElement Object ( [Name] => message12413346907303 [Attribute] => Array ( [0] => SimpleXMLElement Object ( [Name] => active [Value] => 1 ) [1] => SimpleXMLElement Object ( [Name] => user [Value] => fred ) [2] => SimpleXMLElement Object ( [Name] => message [Value] => This is another message ) [3] => SimpleXMLElement Object ( [Name] => time [Value] => 1241334690 ) [4] => SimpleXMLElement Object ( [Name] => id [Value] => 12413346907303 ) [5] => SimpleXMLElement Object ( [Name] => ip [Value] => 10.10.10.2 ) ) ) )

So what code do I need to get through each of the object items? I’d like to loop through each of them and handle it like a returned mySQL query. For example, I can query SimpleDB and then loop though the SimpleXML so I can display the results on the page. Alternatively, how do you turn the whole shebang into an array? I’m new to SimpleXML, so I apologise if my questions aren’t specific enough.

Источник

Оцените статью