0

如何以这种格式使用php获取外部文件的xml数组

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

当我运行此代码时,返回以下结果:
Bondi Beach -33.890542 151.274856 4 Coogee Beach -33.923036 151.259052 5 Cronulla Beach -34.028249 151.157507 3
我必须进行哪些更改才能返回具有以下格式的数组?:

这是我的数组 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>
4

3 回答 3

1

好吧,我看错了问题。试试这个。

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++;
}
于 2013-01-25T00:37:57.420 回答
1
<?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>';
?>

如果你希望数组是关联的,你可以替换这一行:

$locations[] = array('name'=>$name,'latitude'=>$lat,'longitude'=>$long,'id'=>$id);
于 2013-01-25T00:57:15.037 回答
1

您是否尝试过 simplexml - 我正在使用它从外部 xml 源调用数据,它很有效!

$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 />";

}

如果您已经尝试过,请道歉......但如果您还没有尝试过,值得一试!

于 2013-01-25T00:59:13.317 回答