php simplexml具有唯一值

时间:2014-06-18 07:21:55

标签: php xml xpath simplexml

我有一个xml文件并使用simplexml:

   $xml = simplexml_load_file('feed.xml', 'SimpleXMLElement', LIBXML_NOCDATA);

   foreach($xml->item as $products)
     {
     $name =  (string)trim($products->name) ;
     $weight = (string)$products->weight;

     .....and so on...

xml Feed如下:

   <?xml version="1.0"?>
    <root>
    <update_time>2014-06-09</update_time>

    <item>
    <name>Product 1</name>
    <weight>0.3000</weight>
    <Price>31.4400</Price>
    </item>

   <item>
    <name>Product 2</name>
    <weight>0.2000</weight>
    <Price>32.4400</Price>
    </item>

  <item> //duplicate
    <name>Product 1</name>
   <weight>0.1000</weight>
   <Price>22.4400</Price>
   </item>

   </root>      

名称值有重复,我只需要没有重复的值。我需要消除具有重复名称child的整个项目节点(所有孩子)。

我已经读过这可以用xpath完成。我怎么能在上面的代码中做到这一点?可以在foreach循环中使用xpath吗?很困惑如何在我的代码中加入它。

请求帮助..

1 个答案:

答案 0 :(得分:0)

如果您只想选择唯一值并准备插入数据库,那么简单的foreach循环就足够了。请考虑以下示例:Sample Output

$raw_xml = '<?xml version="1.0"?><root><update_time>2014-06-09</update_time><item><name>Product 1</name><weight>0.3000</weight><Price>31.4400</Price></item><item><name>Product 2</name><weight>0.2000</weight><Price>32.4400</Price></item><item><name>Product 1</name><weight>0.1000</weight><Price>22.4400</Price></item></root>';
$xml = simplexml_load_string($raw_xml);
$items = json_decode(json_encode($xml), true);
$update_time = $items['update_time'];
$items = $items['item'];
$new_items = array();
foreach($items as $value) {
    if(!isset($new_items[$value['name']])) {
        $new_items[$value['name']] = $value;
    }
}

$new_items = array_values($new_items);
// $new_items should have unique values

$new_items应该产生:

Array
(
    [0] => Array
        (
            [name] => Product 1
            [weight] => 0.3000
            [Price] => 31.4400
        )

    [1] => Array
        (
            [name] => Product 2
            [weight] => 0.2000
            [Price] => 32.4400
        )

)

插入数据库:

// insert to database
$dbh = new PDO('mysql:host=localhost;dbname=test', 'test', 'test');
foreach($new_items as $key => $value) {
    $stmt = $dbh->prepare("INSERT INTO products (name, weight, price) VALUES (:name, :weight, :price)");
    $stmt->execute(array(':name' => $value['name'], ':weight' => $value['weight'], ':price' => $value['Price']));
}