2013-01-25 49 views
0

当我运行该代码返回以下结果如何以这种形式获得XML数组用PHP,外部文件如何使用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++; 
      } 

的:
邦迪海滩-33.890542 151.274856 4 Coogee海滩-33.923036 151.259052 5克罗纳拉海滩-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> 
+0

我把它你想使用的格式为JavaScript? –

+1

不,php数组格式 – Kakitori

回答

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); 
+0

谢谢,它工作正常! – Kakitori

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

如果我这样说,它会返回错误 – Kakitori

+0

你能粘贴你得到的错误吗? – Tristan

+0

是的,致命的错误:调用未定义的方法DOMElement :: item() – Kakitori

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

} 

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