Sorry I'm new to PHP. I was just starting to learn, so my concepts are taken from C programming. I could do an excessive amount of work / coding here ... but I'm sure I will scream to someone and find out.
This returns the array back, which is well laid out to access all individual bits of data without the need to process SimpleXMLElement objects:
public $xmlFileInName = 'sample.xml'; public $errorMessage = "Failed to open file: "; public function actionGetArray() { try { $xml = file_exists($this->xmlFileInName) ? simplexml_load_file($this->xmlFileInName) : exit($this->errorMessage. $this->xmlFileInName); $xmlArray=$this->arrayFromSxe ($xml); echo var_dump($xmlArray); } catch(Exception $e) { echo $e->getMessage(); } } public function arrayFromSxe($sxe) { $returnArray = array(); foreach ((array)$sxe as $key=>$value) { if(is_array($value) && !$this->is_assoc($value)) { $indies = array(); foreach($value as $secondkey=>$secondvalue) $indies[$secondkey] = $this->arrayFromSxe($secondvalue); $returnArray[$key] = $indies; } else { if(is_object($value)) { $returnArray[$key] = $this->arrayFromSxe($value); } else { $returnArray[$key] = $value; } } } return $returnArray; } function is_assoc($array) { return (bool)count(array_filter(array_keys($array), 'is_string')); }
Note that with multiple xml tags, i.e. in your example:
[time-entry] => Array ( [0] => SimpleXMLElement Object ( ... ) [1] => SimpleXMLElement Object ( ... )
You will need to learn something about the structure of the XML file in order to access this in code. This will be returned to the array after calling this line:
$xmlArray=$this->arrayFromSxe ($xml);
What will happen:
[time-entry][0] [time-entry][1]
Thus, your code must know to iterate over all time entries via int indexers or in any situation in which they are multiple occurrences of an xml element.
If what I said does not make sense, do not pay attention to it and just observe and evaluate the code in its current form.
Hope this helps.
vternal3
source share