douren5898 2012-06-21 22:28 采纳率: 100%
浏览 31
已采纳

将xml产品加载到mysql db中,更新productid所在的位置,插入新的地方并删除db中的productid而不是xml

I have a dynamic products xml file that i need to load from an external source and save in a db table. Now i want to keep the xml file which contains current products in synch with what is in the table. so I want to make sure I update products with IDs in both xml and db table, insert new products and delete those products that are obsolete in db table (they are not in xml file) see illustrations below
XML file mapping

Productid->1 and product-name->book,
Productid->2 and Prouct-name->pen

Now table below

ID Name
1 book
3 pencil

Now I want to update product ID 1 with info from xml, insert product ID 2 from xml into table and delete product ID 3 from table since it's not found in xml

Please any help is appreciated.

  • 写回答

1条回答 默认 最新

  • dongzhun6952 2012-06-22 06:17
    关注

    Since you already have the flowchart of the desired process, it should be pretty straightforward.

    I am not doing any data sanitization / escaping, as you do it as per your requirements.

    XML FILE: (save it as testFeed.xml)

    <?xml version="1.0" encoding="UTF-8"?>
    <products>
        <product>
            <id>1</id>
            <name>book</name>
        </product>
        <product>
            <id>2</id>
            <name>pen</name>
        </product>
    </products>
    

    PHP Code:

    <?php
    $xml = simplexml_load_file( 'testFeed.xml' );
    $xpath = $xml->xpath( '//product' );
    
    $feed = array();
    foreach( $xpath as $node ) {
        $feed[(string)$node->id] = (string)$node->name;  // id is key, name is value
    }
    
    // delete all entries from table where the table entries are not in the xml
    $sql = 'DELETE FROM `table` WHERE id NOT IN 
              (' . implode( ',', array_keys( $feed ) ) . ')';
    $run = mysql_query( $sql, $link );
    
    //Now, insert/update - USE MySQL's "INSERT ... ON DUPLICATE UPDATE" feature
    foreach( $xpath as $key => $node ) {
        $sql = 'INSERT INTO `table` (id,name) VALUES ("'.$key.'","'.$node.'") 
                  ON DUPLICATE KEY UPDATE name="'.$node.'";'
        $run = mysql_query( $sql, $link );
    }
    ?>
    

    MySQL INSERT ... ON DUPLICATE UPDATE example here.

    Hope this helps.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 vue3加ant-design-vue无法渲染出页面
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序