2014-06-16 133 views
0

請,我需要解析XML文件與汽車信息。我做了一切在汽車,照片,但我需要額外的表中有id,汽車表id的外鍵,所有的汽車都有隨機的equipment_id。SimpleXML解析多個標籤同名

我需要得到這個進入「裝備」表:

<equipment> 
    <equipment_id>eq_co_driver_airbag</equipment_id> 
    <equipment_id>eq_driver_airbag</equipment_id> 
    <equipment_id>eq_abs</equipment_id> 
    <equipment_id>eq_aut_aircon</equipment_id> 
    <equipment_id>eq_dalk_centr</equipment_id> 
    <equipment_id>eq_el_contr_win</equipment_id> 
    <equipment_id>eq_el_contr_mirrors</equipment_id> 
    <equipment_id>eq_lite_disky</equipment_id> 
    <equipment_id>eq_immobilizer</equipment_id> 
    <equipment_id>eq_mlhovky</equipment_id> 
    <equipment_id>eq_adjustable_drive_wheel</equipment_id> 
    <equipment_id>eq_original_autoradio</equipment_id> 
    <equipment_id>eq_on_board_comp</equipment_id> 
    <equipment_id>eq_steering_booster</equipment_id> 
    <equipment_id>eq_leather_trim</equipment_id> 
    <equipment_id>eq_ASR</equipment_id> 
    <equipment_id>eq_stresni_sibr_el</equipment_id> 
    <equipment_id>eq_ton_skla</equipment_id> 
    <equipment_id>eq_venkovni_teplomer</equipment_id> 
    <equipment_id>eq_adjustable_seat</equipment_id> 
    </equipment> 

我無法創建正確的導入腳本。

這是從我的XML文件中的一個車: http://pastebin.com/Yyr1GXyb

這裏是通過print_r的一輛車的名單: http://pastebin.com/csQpQSDs

我嘗試這樣做:

echo "import equipment .. "; 
foreach ($xml->cars->car->equipment as $data) { 
     mysql_query("INSERT INTO equipment (cars_id, equipment_id) 
     VALUES 
     ($id_car, \"$data->equipment_id\")") 
     or die(mysql_error()); 
    $id_car++; 
} 
echo "OK\n"; 

echo "import equipment .. "; 
foreach ($xml->cars->car as $entry) { 
    foreach ($entry->equipment as $data) { 
     mysql_query("INSERT INTO equipment (cars_id, equipment_id) 
     VALUES 
     ($id_car, \"$data->equipment_id\")") 
     or die(mysql_error()); 
    } 
    $id_car++; 
} 
echo "OK\n"; 

但沒有成功

我想不通。請幫幫我。非常感謝你!

+0

使用DomDocument來代替,這使得它更容易 – Javad

+0

SimpleXML是不可能的?想要使用SimpleXML,我認爲它是可能的。我不知道如何使用DomDocument進行此操作 – Desttro

回答

0

解決!

echo "import equipment .. "; 
foreach ($xml->cars->car as $entry) { 
    foreach ($entry->children()->equipment->equipment_id as $data) { 
    mysql_query("INSERT INTO equipment (cars_id, equipment_id) 
     VALUES 
     ($id_car, \"$data\")") 
     or die(mysql_error()); 
    } 
    $id_car++; 
} 
echo "OK\n"; 
+0

您應該收集一堆行來插入,然後觸發查詢。不適用於單排。甚至更好,使用準備好的語句將數據泵入數據庫。參見[mysqli](http://php.net/mysqli)。 – hakre

+0

甚至更​​好,直接通過Mysql轉換XML。 http://dev.mysql.com/doc/refman/5.5/en/load-xml.html – hakre