0

我正在通过 Web 服务获取 xml 数据

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

我需要将此列表与我的数据库中的“项目”表进行比较,并仅返回其中一个 xml 节点中也存在 id 的行。

XML 可以包含几百个节点,items 表包含 100k 行

什么是最好的方法

4

2 回答 2

0

解析 XML(例如使用SimpleXML)并将所有 id 收集到一个数组中。然后在数据库查询中使用该数组:

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

(请注意,此代码假定 中的所有元素$id_array都保证为整数或正确 SQL 转义。在使用此代码之前,您需要自己确保这一点,否则您将面临 SQL 注入的风险)

于 2012-06-18T11:27:12.950 回答
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
?>

希望这可以帮助。

于 2012-06-18T11:32:08.240 回答