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条)

报告相同问题?

悬赏问题

  • ¥15 C#调用python代码(python带有库)
  • ¥15 矩阵加法的规则是两个矩阵中对应位置的数的绝对值进行加和
  • ¥15 活动选择题。最多可以参加几个项目?
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)
  • ¥20 怎么在stm32门禁成品上增加查询记录功能
  • ¥15 Source insight编写代码后使用CCS5.2版本import之后,代码跳到注释行里面
  • ¥50 NT4.0系统 STOP:0X0000007B