Jump to content

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;
}

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.