Jump to content

[SOLVED] Remove Duplicates from SimpleXML Object


pepes

Recommended Posts

Does anybody know how can i remove duplicate entries from an Simplexml Object.

Here is the code:

$xml = simplexml_load_string($response);
foreach ($xml->Items->Item as $res){
        $title = $res->ItemAttributes->Title;
..

 

I want to remove duplicates by $title and display only the first one.

Thanks an advance.

Link to comment
Share on other sites

You could just rely on the usual override mechanics of an array and recreate the array with unique values...

 

<?php
$xml = simplexml_load_string($response);

$items = &$xml->Items->Item;
$uniqueItems = array();

for($i = count($items)-1; $i >= 0; --$i) {
   $uniqueItems[$items[$i]->ItemAttributes->Title] = &$items[$i];
}

foreach($uniqueItems as $item) {
    $title = $item->ItemAttibutes->Title;
    // ...
}
?>

Link to comment
Share on other sites

Thank you for your quick response, genericnumber1

 

There is a little problem when i use the code, i get the error "Illegal offset type in" on line   

$uniqueItems[$items[$i]->ItemAttributes->Title] = &$items[$i];

 

Do you know what could be wrong?

Thanks again

Link to comment
Share on other sites

What is the type of $xml->Items->Item->ItemAttributes->Title? I assumed it was just a string. If it's an array or another object, you'll need to use a different method.

 

Yes, it is a string. I thought using trim(), but then it will display just one product no matter what.

 

The code  is actually from a script that pulls products from Amazon api, but i get many duplicates with it.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.