xml解析foreach循环+只插入一条记录?

时间:2013-05-19 14:18:18

标签: php mysql xml simplexml

我不能为我的生活弄清楚如何让这段代码处理多条记录。代码工作正常,它只是插入第一条记录然后停止。

Feed:http://online.computicket.com/web/events/search.rss

PHP:

<?php 

$con=mysqli_connect("localhost","vadevco_reticket","3wer5top","vadevco_reticket");

if( ! $xml = simplexml_load_file('feed.xml') ) { 
    echo 'unable to load XML file'; 
} else { 
    foreach( $xml as $event ) { 
$idrandom = rand(0,99);
        $title = $event->item->title; 
        $description = $event->item->description;
        $link = $event->item->link;
        $guid = $event->item->guid;
        $pubDate = $event->item->pubDate;
        $image_t = $event->item->image_thumb;
        $image_l = $event->item->image_large;
        $displayDates = $event->item->displayDates;
$sql = "INSERT INTO `vadevco_reticket`.`events` (`title`, `description`, `pubDate`, `image_t`, `image_l`, `displayDates`, `id`, `event_id`) VALUES ('$title', '$description', '$pubDate', '$image_t', '$image_l', '$displayDates','','$idrandom')";
mysqli_query($con,$sql);

        foreach( $event->item->showDates->showDate as $eventDate ) {        
            $date = $eventDate->date;
            $venue = $eventDate->venue;
            $complex = $eventDate->complex;
            $region = $eventDate->region;
            $costs = $eventDate->costs;
$sql2 = "INSERT INTO `vadevco_reticket`.`instances` (`id`, `event_id`, `date`, `venue`, `complex`, `city`, `region`, `costs`) VALUES ('', '$idrandom', '$date', '$venue', '$complex', '$city','$region','$costs')";
mysqli_query($con,$sql2);
          }


 } 

    } 

?> 

如何让它循环遍历Feed中所有$ item实例并将其全部插入所有建议将非常感激。

提前致谢!

1 个答案:

答案 0 :(得分:2)

您需要遍历项目而不是xml本身:

foreach( $xml->item as $event ) { 
  $idrandom = rand(0,99);
  $title = $event->title; 
  $description = $event->description;
  ...
}