Your main problem is centered around your use of SimpleXML, I don't think you've fully grasped it yet.
With the XML document provided, when the SimpleXML document is parsed (using your
simplexml_load_string) the object is created which represents your XML data. In this case, the
$file variable is essentially the
<desc ... /> node in the form of a PHP object. If we were to take a look at the object (using
print_r($file)) here's what we would see:
Code:
SimpleXMLElement Object
(
[@attributes] => Array
(
[pic] => 1
[info] => Testing
)
)
Because it is that node (the "root node" in XML terminology), you can't access the
desc by trying
$file->desc! To put it simply and hopefully in a straightforward way, you would need to use
$file['@attributes']['pic'] to get a hold of the
pic attribute.
Changes
PHP Code:
$file = simplexml_load_string(file_get_contents($xml));
foreach($file->desc as $desc) {
if($desc['pic'] == $id) {
echo $desc['info'];
}
}
PHP Code:
// See: http://php.net/simplexml_element_construct
// for an explanation of the arguments used here
$desc = new SimpleXMLElement($xml, null, true);
echo $desc['@attributes']['info'];
However, if you're wanting to have descriptions for multiple images in your XML document -- like below -- things will be slightly different. Let us know if that's the case!
Do you want multiple descs?
(I've just changed the names to make more sense to me.)
Code:
<?xml version="1.0" encoding="utf-8"?>
<pics>
<pic id="1" info="Testing!" />
<pic id="2" info="Testing again!" />
<pic id="3" info="Testing again, again!" />
</pics>