Jump to content

SimpleXMLElement To Array


RobertP

Recommended Posts

i am working on a method that will parse an simplexml to an array

 

if you notice any thing odd or incorrect please let me know

 

	private function parseResponse(SimpleXMLElement $response){
	$parsedResponse = array();
	if(method_exists($response,'attributes')){
		$parsedResponse['attributes'] = array();
		foreach($response->attributes() as $key => $value)
			$parsedResponse['attributes'][lcfirst((string)$key)] = (string)$value;
	}
	if($response->count()>0){
		foreach($response->children() as $value)
			$parsedResponse[] = $this->parseResponse($value);
	}
	return $parsedResponse;
}

 

Link to comment
https://forums.phpfreaks.com/topic/266969-simplexmlelement-to-array/
Share on other sites

PEAR has a handy class for that XML_Unserializer

 

http://pear.php.net/manual/en/package.xml.xml-serializer.xml-unserializer.getunserializeddata.php

 

Or the Serializer component from Symfony components.

 

https://github.com/symfony/serializer

i am creating an api that connects to various xmlrcp servers that i use often. my api will replace a large section of my website network.

 

updated version:

 

	private function parseResponse($response,&$parsedResponse = array()){
	foreach($response->children() as $elementName => $node){
		$nextIdx = count($parsedResponse);
		$parsedResponse[$nextIdx] = array();
		$parsedResponse[$nextIdx]['@name'] = (string)$elementName;
		if(count($node->attributes())>0){
			$parsedResponse[$nextIdx]['@attributes'] = array();
			foreach($node->attributes() as $attributeName => $attributeValue)
				$parsedResponse[$nextIdx]['@attributes'][trim((string)$attributeName)] = trim((string)$attributeValue);
		}
		$text = trim((string)$node);
		if(strlen($text)>0)
			$parsedResponse[$nextIdx]['@text'] = $text;
		if($node->count()>0){
			$parsedResponse[$nextIdx]['@children'] = array();
			$this->parseResponse($node,$parsedResponse[$nextIdx]['@children']);
		}
	}
	return $parsedResponse;
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.