Reputation: 913
how to get an array of xml with php in this format, of an external file
$locations = array(
(Bondi Beach, -33.890542, 151.274856, 4),
(Coogee Beach, -33.923036, 151.259052, 5),
(Cronulla Beach', -34.028249, 151.157507, 3)
);
//this is my file php
$dom = new DOMDocument();
$dom->load('school.xml');
$students = $dom->getElementsByTagName('student');
$i = 0;
foreach ($students as $student) {
$locations = $students->item(0)->nodeValue;
echo $locations;
$i++;
}
when I run this code returns the following result:
Bondi Beach -33.890542 151.274856 4 Coogee Beach -33.923036 151.259052 5 Cronulla Beach -34.028249 151.157507 3
What do I have to change so that It return an array with the following format?:
this is my array school.xml
<school>
<student>
<name>Bondi Beanch</name>
<latitude>-33.890542</latitude>
<longitude>151.274856</longitude>
<id>4</id>
</student>
<student>
<name>Coogee Beach</name>
<latitude>-33.923036</latitude>
<longitude>151.259052</longitude>
<id>5</id>
</student>
<student>
<name>Cronulla Beach</name>
<latitude>-34.028249</latitude>
<longitude>151.157507</longitude>
<id>3</id>
</student>
</school>
Upvotes: 0
Views: 261
Reputation: 2399
Okay, I misread the problem. Try this.
foreach ($students as $key => $student) {
$locations[] = array($student->childNodes->item(0)->nodeValue, $student->childNodes->item(1)->nodeValue, $student->childNodes->item(2)->nodeValue, $student->childNodes->item(3)->nodeValue);
$i++;
}
Upvotes: 1
Reputation: 127
Have you tried simplexml - I am using it to call data from an external xml source and it works a treat !
$xml= simplexml_load_file('school.xml')
or Die ('ERROR: Could Not connect to File!');
foreach($xml->student as $student) {
$name = $student->name;
$latitude = $student>latitude;
$longitude = $student->longitude;
$id = $student->id;
echo "<b>" . "Name: " . "</b>" . $name . " <br />";
echo "<b>" . "Latitude: " . "</b>" . $latitude . " <br />";
echo "<b>" . "Longitude: " . "</b>" . $longitude . " <br />";
echo "<b>" . "id: " . "</b>" . $id . " <br />";
}
Apologies if you have already tried it... but worth a shot if you haven't !
Upvotes: 1
Reputation: 16828
<?php
$dom = new DOMDocument();
$dom->load('school.xml');
$students = $dom->getElementsByTagName('student');
foreach ($students as $student){
foreach($student->childNodes as $node){
switch($node->nodeName){
case 'name':
$name = $node->nodeValue;
break;
case 'longitude':
$long = $node->nodeValue;
break;
case 'latitude':
$lat = $node->nodeValue;
break;
case 'id':
$id = $node->nodeValue;
break;
}
}
$locations[] = array($name,$lat,$long,$id);
}
echo '<pre>';
print_r($locations);
echo '</pre>';
?>
and if you wanted the arrays to be associative you could replace this line:
$locations[] = array('name'=>$name,'latitude'=>$lat,'longitude'=>$long,'id'=>$id);
Upvotes: 1