用php解析xml(在xml元素上使用for循环创建多维数组)



我有一个file.xml文件夹在…这个文件是:

<xml>
 <alert>
  <info>
   <area>
    <circle>18.980,153.480 0</circle>
   <area>
  </info>
  <info>
   <area>
    <circle>28.980,163.480 0</circle>
   <area>
  </info>
  <info>
   <area>
    <circle>38.980,173.480 0</circle>
   <area>
  </info>
 </alert>

我有一个空数组,我想创建一个多维数组在元素圈的数字,所以我必须做一个for循环,但在我的文件xml我不知道有多少信息。

$url = "outvulcani/report.xml";
$xml = simplexml_load_file($url);
$numinfo = substr_count($xml, "<info>");
for ($i = 0; $i <= $numinfo; $i++) {

$entry = $xml->alert->info[$i];
$coordinate = $entry->area->cirle;
$virgola = strpos($coordinate,",");
$spazio = strpos($coordinate," ");
$virg = $virgola;
$virgLng = $virgola+1;
$spaz = $spazio-$virgola;   
$lat = substr($coordinate,0,$virg);
$lng = substr($coordinate,$virgLng,$spaz);
$report[] = array($lat,$lng);
}

结尾,我希望数组$report是:

Array
(
      [0] => Array
        (
            [0] => 18.980
            [1] => 153.480 
        )
     [1] => Array
        (
            [0] => 28.980
            [1] => 163.480 
        )
     [2] => Array
       (
        [0] => 38.980
        [1] => 173.480 
      )
 )

这应该能奏效。不过,这个XML看起来并不有效。区域标签需要关闭

测试XML文件

<alert>
  <info>
   <area>
    <circle>18.980,153.480 0</circle>
   </area>
  </info>
  <info>
   <area>
    <circle>28.980,163.480 0</circle>
   </area>
  </info>
  <info>
   <area>
    <circle>38.980,173.480 0</circle>
   </area>
  </info>
</alert>

更新脚本
$xml = simplexml_load_file('example.xml');
$result = [];
foreach ($xml->info as $info) {
    $result[] = explode(',', $info->area->circle);
}
print_r($result);
结果

Array                        
(                            
    [0] => Array             
        (                    
            [0] => 18.980    
            [1] => 153.480 0 
        )                    
    [1] => Array             
        (                    
            [0] => 28.980    
            [1] => 163.480 0 
        )                    
    [2] => Array             
        (                    
            [0] => 38.980    
            [1] => 173.480 0 
        )                    
)                            

相关内容

  • 没有找到相关文章

最新更新