duandu6497 2011-08-15 18:47
浏览 98
已采纳

PHP拆分数组变量

I am extracting XML from a feed. There is a tag entitled:

<georss:point>34.234 -34.435</georss:point> 

which contains two variables I am inserting into MySQL When I run this code, the variable is 'array'. I then place an extract to break out the variables, unsure of next

$xmlString = str_replace('georss:point','point',$xmlString);  
$xml = new SimpleXMLElement($xmlString); 
$items = $xml->xpath('channel/item'); 
$closeItems = array(); 
foreach($items as $item) 
{     
    $latlng = explode(' ',trim($item->point));
    array(
            'lat'=>$latlng[0],
            'lng'=>$latlng[1]
    );

    $lat = array($latlng[0]);
    $lng = array($latlng[1]);

    echo $lat;
    echo $lng;  
} 

When I place those echo statements (in the last two lines of code), the variables get echod to the screen. However when I place these varaibles outside of the array, the values do not get echod. I am attempting to get these variables outside of the array, so that I can insert these variables into the database. I have tried extract on the varaiables, but this prints back to the screen as 'Array'... unsure of what I need to do to extract these variables from the array. Thanks,

  • 写回答

4条回答 默认 最新

  • doulu5717 2011-08-15 18:53
    关注

    Some observations.

    1) you can register xpath namespaces instead of replacing in the string
    2) array('lat'=>$latlng[0],'lng'=>$latlng[1]); does nothing. It is a dead store.
    3) Instead of

    $lat = array($latlng[0]);
    $lng = array($latlng[1]);
    echo $lat;
    echo $lng;  
    

    You can do: echo $latlng[0].'-'.$latlng[1];
    If you try to echo an array, you will always get Array.
    Use a specific index to echo an individual element.

    4) Alternatively you could use list to store the variables directly
    list($lat, $long) = explode(' ',trim($item->point));

    Edit To insert multiple results into your database, store the results in an array:

    $lat_long = array();
    foreach($items as $item){
        $lat_long[] = explode(' ', $item);
    }
    

    Then later iterate through this array and do your database insert.

    foreach($lat_long as $point){   
      //do SQL injection prevention as well
      //INSERT INTO your_table (`lat`, `long`) VALUES ($point[0], $point[1]);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型