tags:

views:

147

answers:

4

I'm getting "illegal offset type" error for every iteration of this code. Here's the code in case anyone can help:

$s = array();

for($i=0;$i<20;$i++){

    $source = $xml->entry[$i]->source;
    $s[$source] += 1;

}

print_r($s)

Any ideas. Thanks in advance.

+2  A: 

There are probably less than 20 entries in your xml.

change the code to this

for ($i=0;$i< sizeof($xml->entry); $i++)
...
Byron Whitlock
thanks but it's not that.
Steven
An undefined integer index doesn't generate an "Illegal offset" warning, you'd get an "Undefined index" E_NOTICE instead.
zombat
A: 
var_dump($source);
Col. Shrapnel
+1  A: 

Illegal offset type errors occur when you attempt to access an array index using an object or an array as the index key.

Example:

$x = new stdClass();
$arr = array();
echo $arr[$x];
//illegal offset type

Your $xml array contains an object or array at $xml->entry[$i]->source for some value of $i, and when you try to use that as an index key for $s, you get that warning. You'll have to make sure $xml contains what you want it to and that you're accessing it correctly.

zombat
the source contains html, does that class as an object?
Steven
Did you create the `$xml` variable using some kind of XML parser? simple_xml or DOMDocument? In that case, then it's likely that the source node is actually some kind of dom element object.
zombat
i'm using simplexml_load_string. does that help?
Steven
Your HTML might have been parsed as XML, and likely all your tags became nodes. For example, if you had an HTML snippet of "<div>Hi</div>" as your source property, then you've probably got something like `$xml->entry[$i]->source->div`. If you want to parse HTML into a DOM structure, `DomDocument` has a `loadHTML()` function that handles HTML much better than SimpleXML. Check out http://www.php.net/manual/en/domdocument.loadhtml.php
zombat
thanks for that. I've used str_replace to strip the html and it works.
Steven
nice! glad you got it working.
zombat
A: 

check $xml->entry[$i] exists and is an object before trying to get a property of it

 if(isset($xml->entry[$i]) && is_object($xml->entry[$i])){
   $source = $xml->entry[$i]->source;          
   $s[$source] += 1;
 }

or $source might not be a legal array offset but an array, object, resource or possibly null

brian_d