OK, I am ready to smash my head on the table. Would someone please tell me why this doesn't work:
<?php
$xml = simplexml_load_file('images.xml');
$src = $xml->album->img[0]->attributes()->src; // OK $src = $xml->album->img[1]->attributes()->src; // OK $src = $xml->album->img[2]->attributes()->src; // OK $id = $_GET['id']; $src = $xml->album->img[$id]->attributes()->src; // Fail
?>
Thanks in advance.
Are you sure $_GET['id'] is a 0, 1, or 2?
Yep. http://localhost/~mwk/dev/xml/image_list3.php?id=1
Also something odd: if I add a big ol' switch block at the top of the script:
<?php if (isset($GET['id'])) { if ($GET['id'] == 0) {$id = 0;} if ($GET['id'] == 1) {$id = 1;} if ($GET['id'] == 2) {$id = 2;} if ($GET['id'] == 3) {$id = 3;} if ($GET['id'] == 4) {$id = 4;} if ($_GET['id'] == 5) {$id = 5;} } else { $id = 0; } ?>
Then it will work. Any insight would be hugely appreciated.
Maybe it's a type thing? How about replacing those ifs with:
$id = (isset($_GET['id'])) ? (int)$_GET['id'] : 0;
You are brilliant! Yes, that did the job.
I had no idea PHP supported variable types. Obviously I need to brush up on my fundamentals.
Seriously, thank you, I was completely stumped.
Best,
Mike
Normally PHP is "loosely typed" and will automatically cast to the appropriate type. According to the Array Type documentation, When you use a string key that can be directly interpreted as an integer, it should be used as a numeric array index and not an associative array string key. So now I wonder if it's something going on within the SimpleXML code itself, and whether it's a bug or a feature. :rolleyes:
But a SimpleXML element like $xml->album->img isn't actually an array (it's got properties for its attributes, for example) - it's an object that has had an array access interface added. Somewhere down in its implementation of the access interface it doesn't do a string=>integer conversion. Perhaps this should be addressed in bugs.php.net if it hasn't been already.