2011-12-31 81 views
0

我想插入XML数据到MySQL数据库。我遇到的问题是每个标签中都有多个id,因此我的脚本只加载第一个标签。我如何重新编写我的脚本来加载所有的ID到数据库,每行一个ID。插入简单的XML列表到mySQL

<?php 

require_once 'db-functions.inc.php' ; //custom database functions 

$xmldata = 'http://api.twitter.com/1/followers/ids.xml?cursor=-1&screen_name=aplusk'; 
$open = fopen($xmldata, 'r'); 
$content = stream_get_contents($open); 
fclose($open); 
$xml = new SimpleXMLElement($content); 

foreach ($xml->ids as $data) 

{ 

$id = $data->id; 

mysql_query("INSERT INTO data (id) 

VALUES ('$id')"); 

}; 


// sample of xml I want to insert 
// <id_list> 
// <ids> 
// <id>275168965</id> 
// <id>28245852</id> 
// <id>15112249</id> 
// </ids> 
// <next_cursor>0</next_cursor> 
// <previous_cursor>0</previous_cursor> 
// </id_list> 

?> 
+0

你为什么要调用'new SimpleXMLElement()'两次?同样,从数据看来,您需要''foreach'' ids'而不是'id_list',例如:'foreach($ twelement-> id_list-> id为$ data)''id_list'实际上只有一个元素,而不是包含id的'id'元素。 – Yaniro 2011-12-31 17:07:11

+0

当我像上面的foreach($ twelement-> id_list-> id为$ data)一样编辑foreach时,出现错误,插入语句是否正确? – WAUS 2012-01-07 03:57:54

回答

0

这里是你应该怎么做:

$xml = new SimpleXMLElement(file_get_contents('http://api.twitter.com/1/followers/ids.xml?cursor=-1&screen_name=aplusk')); 
foreach ($xml->ids[ 0 ] as $data) 
{ 
    echo($data . "<br>"); 
} 

它并不直观,但IDS需要在$ XML的隐藏> IDS [0]。 你的SQL语句看起来不错。

+0

非常感谢,效果很好。 – WAUS 2012-01-08 01:30:55