Getting child and sub-child elements from XML in PHP with SimpleXMLElement
12:40 25 Oct 2014

Okay, what should be a simple little task has already cost me three days! I am working with PHP on OS X 10.6.8 and for various reasons cannot upgrade to Mavericks, so I am stuck without a proper PHP IDE and damned to TextWrangler.

So here's my XML:




    0001
    
        photo1.jpg
        photo2.jpg
        photo3.jpg
        photo4.jpg
    
    AVENUE RIVIERA


    0002
    
        photo1.jpg
        photo2.jpg
        photo3.jpg
        photo4.jpg
    
    AVENUE RIVIERA


    0003
    
        photo1.jpg
        photo2.jpg
        photo3.jpg
        photo4.jpg
    
    AVENUE RIVIERA


I have figured out how to cycle through the annonce elements to extract each sub attribute so that I can write them all to my database table annonce:

$xmlFile = simplexml_load_file($file);

foreach($xmlFile->annonce as $annonce)
{
    foreach($annonce->children() as $child)
    {
        ...
        echo $child->getName().": ".(string)$child."
"; } }

What I want to be able to do is cycle through the photos, recuperating each photo as well as the referent to the annonce (the relationship photo to annonce is many-to-one). When I insert the code into the foreach($annonce->children() as $child) space, nothing shows up for the photos:

$xmlFile = simplexml_load_file($file);

foreach($xmlFile->annonce as $annonce)
{
    foreach($annonce->children() as $child)
    {
        ...
        echo $child->getName().": ".(string)$child."
"; foreach ($child->{"liste_photos"} as $liste_photos) { foreach ($liste_photos->{"photo"} as $photo) { ... echo $photo->getName().": ".(string)$photo."
"; } } } }

What am I doing wrong??

php xml simplexml