2

Counting values with the following code turns no results to my array. Would appreciate any help on what I did wrong thanks.

$xml=simplexml_load_file("sitemap.xml");

$arr = array();
foreach($xml->url as $child)
{
    if (isset($child->loc)) {
        echo "true";
        $arr[] = $child->loc;
    } else {
        echo "error";
        echo  $child->loc; 
    }        
}
print_r(array_count_values($arr));
7
  • What this extra ?> for? Commented Sep 2, 2013 at 6:36
  • My bad removed a content earlier. Commented Sep 2, 2013 at 6:37
  • count($arr) is also counts the no of entities of an array Commented Sep 2, 2013 at 6:37
  • Actually I want to count duplicates. Commented Sep 2, 2013 at 6:37
  • 1
    Can you show var_dump($arr) and var_dump(array_count_values($arr))? Commented Sep 2, 2013 at 6:39

3 Answers 3

2

You have to cast the item values properly, otherwise you would be storing SimpleXMLElement objects in your array:

$arr[] = (string)$child->loc;
Sign up to request clarification or add additional context in comments.

Comments

0

May be expecting like this

$xml=simplexml_load_file("sitemap.xml");

echo "<pre>";
var_dump($xml->url->loc[0]);
var_dump($xml->url->loc[1]);
var_dump($xml->url->loc[2]);

echo "</pre>";

$arr = array();

foreach($xml->url as $child)
{
    foreach($child as $tmp){    
        if (isset($tmp)) {
            echo "true";
            $arr[] = (String)$child->loc;
        } else {
            echo  "error<br/>";
            echo  $child->loc; 
        }    
    }    
}
print_r(array_count_values($arr));



<sites>
    <url>
        <loc>google.com</loc>
        <loc>google.com</loc>
        <loc>yahoo.com</loc>
    </url>
</sites>

Comments

0

Solution formed after the answer of jack. Added this code to check for duplicates.

if(count($arr) != count(array_unique($arr))){
      echo "Duplicates";
   }

1 Comment

I guess that's debugging code, but if count($arr) doesn't equal count(array_unique($arr)) that means there are duplicates.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.