xml - php simplexml with unique values -
xml - php simplexml with unique values -
i have xml file , using simplexml :
$xml = simplexml_load_file('feed.xml', 'simplexmlelement', libxml_nocdata); foreach($xml->item $products) { $name = (string)trim($products->name) ; $weight = (string)$products->weight; .....and on...
the xml feed follows:
<?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>
the name value had duplicates , need values without duplicates. need eliminate whole item node (all children) duplicate name child.
i have read can done xpath. how can in above code?? can xpath used within foreach loop? pretty confused on how incorporate in code above.
help requested..
if want select unique values , prepare insertion in database, simple foreach loop should suffice. consider example: 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 $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
should yield:
array ( [0] => array ( [name] => product 1 [weight] => 0.3000 [price] => 31.4400 ) [1] => array ( [name] => product 2 [weight] => 0.2000 [price] => 32.4400 ) )
insert database:
// insert database $dbh = new pdo('mysql:host=localhost;dbname=test', 'test', 'test'); foreach($new_items $key => $value) { $stmt = $dbh->prepare("insert products (name, weight, price) values (:name, :weight, :price)"); $stmt->execute(array(':name' => $value['name'], ':weight' => $value['weight'], ':price' => $value['price'])); }
php xml xpath simplexml
Comments
Post a Comment