我有一个工作代码
<?php
$con = mysql_connect('localhost','test','test');
mysql_select_db('test',$con);
require_once("xml2json.php");
$testXmlFile = 'myxml.xml';
$xmlStringContents = file_get_contents($testXmlFile);
$jsonContents = "";
$jsonContents = xml2json::transformXmlStringToJson($xmlStringContents);
$obj =json_decode($jsonContents);
$rows = array();
foreach($obj->rss->channel->item as $item) {
$rows[] = "('".mysql_real_escape_string($item->title)."','".mysql_real_escape_string($item->description)."')";
}
$del_horoscope = "delete from jos_horoscope";
mysql_query($del_horoscope);
$query = "INSERT INTO `jos_horoscope` (`title`,`description`) VALUES ".implode(', ',$rows);
print_r ($query);
mysql_query($query);
// Do the query - do NOT show the output of mysql_error() in a production environment!
if (!mysql_query($query)) echo 'Oh no! Something went wrong with the query: '.mysql_error();
?>
但是每次运行此脚本时,数据都会插入两次。我正在使用delete语句在插入新数据之前先删除数据。任何人都可以帮我解决这个问题。这是两次填充数据的屏幕截图。http://i.imgur.com/7IM1mOE.png?1
NEW EDIT
这是INSERT QUERY echo http://pastebin.com/btZ7f85a 数据不重复。
提前致谢
答案 0 :(得分:0)
这是未经测试的,但请尝试这样的事情。我将删除更改为TRUNCATE,这将删除表中的所有数据。我也改变了INSERT的工作方式,而不是1长插入我将其更改为多个插入。不应该有巨大的性能损失。试一试,让我知道。
<?php
$con = mysql_connect('localhost','test','test');
mysql_select_db('test',$con);
require_once("xml2json.php");
$testXmlFile = 'myxml.xml';
$xmlStringContents = file_get_contents($testXmlFile);
$jsonContents = xml2json::transformXmlStringToJson($xmlStringContents);
$obj =json_decode($jsonContents);
$rows = array();
foreach($obj->rss->channel->item as $item)
{
$rows[] = "('".mysql_real_escape_string($item->title)."','".mysql_real_escape_string($item->description)."')";
}
// Remove Data in Table.
$truncate = mysql_query("TRUNCATE TABLE jos_horoscope");
foreach($rows as $row)
{
$query = "INSERT INTO `jos_horoscope` (`title`,`description`) VALUES $row";
$result = mysql_query($query) or die(mysql_error());
}
?>