SimpleXML is just as dodgy. I have used it lately, trying to make configuration files βeasierβ to write and find out in the process that SimpleXML does not always work in concert. In this case, I think it will be useful for you to simply determine if the <property> only one in the set, and if so, first wrap it in an array, and then send it to your loop.
NOTE: ['root'] is there because I needed to wrap the '<root></root>' element around your XML so that my testing work.
//Rebuild the properties listings $rebuild = array(); foreach($xml_array['root']['branch'] as $key => $branch) { $branchName = $branch['@attributes']['name']; //Check to see if 'properties' is only one, if it //is then wrap it in an array of its own. if(is_array($branch['properties']['property']) && !isset($branch['properties']['property'][0])) { //Only one propery found, wrap it in an array $rebuild[$branchName] = array($branch['properties']['property']); } else { //Multiple properties found $rebuild[$branchName] = $branch['properties']['property']; } }
This will help restore your properties. It feels a bit hacked. But basically you find the lack of a multidimensional array here:
if(is_array($branch['properties']['property']) && !isset($branch['properties']['property'][0]))
If you do not find a multidimensional array, you will obviously make one of the single <property> . Then, to verify that everything was restored correctly, you can use this code:
//Now do your operation...whatever it is. foreach($rebuild as $branch => $properties) { print("Listings for $branch:\n"); foreach($properties as $property) { print("Reference of " . $property['reference'] . " sells at $" . $property['price'] . " for " . $property['bedrooms'] . " bedrooms.\n"); } print("\n"); }
This leads to the following conclusion:
Listings for Trustee Realtors: Reference of 1 sells at $275000 for 3 bedrooms. Reference of 2 sells at $350000 for 4 bedrooms. Reference of 3 sells at $128500 for 4 bedrooms. Listings for Quick-E-Realty Inc: Reference of 4 sells at $180995 for 3 bedrooms.
And the rebuild dump will create:
Array ( [Trustee Realtors] => Array ( [0] => Array ( [reference] => 1 [price] => 275000 [bedrooms] => 3 ) [1] => Array ( [reference] => 2 [price] => 350000 [bedrooms] => 4 ) [2] => Array ( [reference] => 3 [price] => 128500 [bedrooms] => 4 ) ) [Quick-E-Realty Inc] => Array ( [0] => Array ( [reference] => 4 [price] => 180995 [bedrooms] => 3 ) ) )
I hope this helps you get closer to solving your problem.
Crackertastic
source share