2012-06-17 50 views
0

我通過網絡服務中獲取XML數據比較XML的數據到MySQL表

<ITEMS> 
    <item id="uilldmduw"/> 
    <item id="wl2323ldsaw"/> 
</ITEMS> 

我需要這個名單比作「項目」表上我的資料庫,並返回僅具有一個id行時,也存在於其中一個xml節點中。

XML可以包含幾百節點,項目表中包含的行

什麼將是最好的辦法

回答

0

解析XML(例如使用SimpleXML),並收集所有的ID到一個數組的100K的。然後使用該數組在數據庫中查詢:

$query = sprintf('SELECT id, field, field2 
        FROM table 
        WHERE 
        id IN(%s)', 
       implode(',', $id_array)); 

(請注意,此代碼假定在$id_array所有元素要麼是保證是整數或正確SQL轉義您需要在使用前確保這個自己。這個代碼,否則你冒SQL注入的風險)

0

下面給出一個在xml文件中有一個id的所有行的列表。

<?php 
$xml = '<ITEMS> 
     <item id="uilldmduw"/> 
     <item id="wl2323ldsaw"/> 
    </ITEMS>'; 
$xml = simplexml_load_string($xml); 

// do an xpath query and get all item id's 
$result = $xml->xpath('//item[@id]'); 

$idList = array(); 
foreach($result as $node) { 
    $idList[] = '"' . (string)$node[ 'id' ] . '"'; 
} 

// all id's are now in a string sequence 
$idList = implode(',', $idList); 

$results = array(); 

// select all rows which have an id in the sequence 
$sql = 'SELECT * FROM `table` WHERE `id` IN (' . $idList . ')'; 
$run = mysql_query($sql, $db_conn); 

if($run && mysql_num_rows($run)) { 
    while(($fetch=mysql_fetch_assoc($run))!=false) { 
     $result[] = $fetch;//store the results the way you want. 
    } 
} 

//$results now contains the desired result 
?> 

希望這會有所幫助。