SimpleXML解析具有相同名称的多个标记

时间:2014-06-16 17:11:04

标签: php mysql xml parsing simplexml

拜托,我需要解析带有汽车信息的XML文件。我在汽车,照片上做了一切,但我需要在额外的表中有id,汽车表的id的外键,以及所有汽车随机的equipment_id。

我需要把它变成"设备"表:

  <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";

但没有成功

我无法弄明白。请帮我。非常感谢你!

1 个答案:

答案 0 :(得分: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";