Skip to content

Instantly share code, notes, and snippets.

@insaurabh
Last active September 26, 2018 18:51
Show Gist options
  • Save insaurabh/ffd9e097c2dce3183e325a0e03918ff4 to your computer and use it in GitHub Desktop.
Save insaurabh/ffd9e097c2dce3183e325a0e03918ff4 to your computer and use it in GitHub Desktop.
Practising xml to array and php loops
<?php
$url = 'fileName.xml';
$xml = simplexml_load_file($url); // load
$jsonEncode = json_encode($xml); // encode
$arrayData = json_decode($jsonEncode,TRUE); // decode , that's it now every thing is in array no need to query as object or parse to string
dump($arrayData['residential'][0]['agentID']);
dump($arrayData['residential'][0]['uniqueID']);
dump($arrayData['residential'][0]['tenancy']);
dump($arrayData['residential'][0]['price']);
dump($arrayData['residential'][0]['landDetails']['area']);
dump($arrayData['residential'][0]['landDetails']['frontage']);
dump($arrayData['residential'][0]['listingAgent'][0]['name']);
dump($arrayData['residential'][0]['listingAgent'][0]['telephone'][0]);
dump($arrayData['residential'][0]['listingAgent'][0]['telephone'][1]);
dump($arrayData['residential'][0]['description']);
// list of images from xml
$imgArrayList = $arrayData['residential'][0]['objects']['img'];
$count = count($imgArrayList);
if($count > 0) {
$imgUrlArray = [];
foreach ($imgArrayList as $key => $value) {
foreach ($value as $key => $attributes) {
if(isset($attributes['url'])) {
$imgUrlArray[] = $attributes['url'];
}
}
}
}
dump($imgUrlArray);
// output
Array
(
[0] => http://image-url/1P0001/inrsaurabh.jpg
[1] => http://image-url/1P0002/inrsaurabh.jpg
[2] => http://image-url/1P0003/inrsaurabh.jpg
[3] => http://image-url/1P0004/inrsaurabh.jpg
[4] => http://image-url/1P0005/inrsaurabh.jpg
[5] => http://image-url/1P0007/inrsaurabh.jpg
[6] => http://image-url/1P00010/inrsaurabh.jpg
[7] => http://image-url/1P0001/inrsaurabh.jpg
[8] => http://image-url/1P0001/inrsaurabh.jpg
[9] => http://image-url/1P0001/inrsaurabh.jpg
)
function dump($data='')
{
echo "<br/><==============================================================><br/>";
echo "<pre>";
print_r($data);
echo "</pre>";
echo "<br/><==============================================================>";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment