extract distinct tag value from xml file using php

using simplexmland xpath:

$xml = simplexml_load_string($x); // assume XML in $x

// create array with all non-unique <contact_no>
$ids = $xml->xpath("/contacts/contact/contact_no");
$ids = array_diff(array_count_values(array_map("strval", $ids)), array("1"));

// select each non-unique entry and delete it
foreach ($ids as $id => $count) {   
    $results = $xml->xpath("/contacts/contact[contact_no = '$id']");
    for ($i = $count; $i > 0; $i--) unset($results[$i][0]); 
} 

see it working: https://eval.in/84939

Comments
line 04: select all <contact_no> and put it into array $ids
line 05: these are objects, so we…
1. use array_map() to convert them to string
2. use array_count_values() to have the contact_no as key and its count as value
3. use array_diff() to remove all unique elements (value = 1)
line 09: select all <contact> with its no stored in $id into $results
line 10: loop through $results and unset() all <contact> but one

Leave a Comment