RafaelM
RafaelM

Reputation: 159

Cannot properly parse XML file

I am trying to parse an XML file using simple_xml_load_file , but for some reason I can only parse the file when it's got more than one record!

This is what I'm trying to parse:

object(SimpleXMLElement)#1 (1) { 
["row"]=> object(SimpleXMLElement)#2 (1) 
    { ["@attributes"]=> array(16) 
        { ["ClientCode"]=> string(3) "259" 
          ["Date"]=> string(23) "2013-08-20T02:29:00.273" 
           ["Name"]=> string(16) "COMPLETE NAME" 
           ["Contact"]=> string(0) "" 
           ["Add1"]=> string(50) "ADDRESS LINE 1" 
           ["Add2"]=> string(0) "" 
           ["City"]=> string(3) "CITY" 
           ["State"]=> string(0) "" 
           ["ZipCode"]=> string(0) "" 
           ["Country"]=> string(4) "COUNTRY" 
           ["Email"]=> string(0) "" 
           ["Phone1"]=> string(13) "PHONE NUMBER" 
           ["Phone2"]=> string(0) "" 
           ["Notas"]=> string(0) "" 
           ["Destination"]=> string(7) "DESTINATION" 
           ["Password"]=> string(0) "" } 
    }
}

I am using this code to do it:

<?php
$xml = simplexml_load_file($data);

foreach($xml->NewDataSet->row[0]->row as $row)    {
    $client_id = $row['ClientCode'];
    $fecha = $row['Date'];
    $nombre =  $row['Name'];
    $direccion1 = $row['Add1'];
    $direccion2 = $row['Add2'];
    $ciudad = $row['City'];
    $estado = $row['State'];
    $pais = $row['Country'];
    $email =  $row['Email'];
    $telefono1 =  $row['Phone1'];
    $telefono2 =  $row['Phone2'];
    $id1 =  $row['ID1'];
    $id2 =  $row['ID2'];

   echo 'These are the details'.$consignee_id.'  '.$nombre.'  '.$email.'<br>';

   }
?>

$data is a file saved on the server that usually has many records. The problem happens when I try to parse a file that contains more than one record for some reason. I do not get any errors or anything, just a blank page. I should be able to access each field of the XML file (name , clientcode,etc.)

What am I doing wrong?

Thanks!

Upvotes: 1

Views: 53

Answers (1)

michi
michi

Reputation: 6625

You have to get the path to <row> right.

Translating your dump to XML:

<NewDataSet>
    <row
        ClientCode = "259"
        Date = "2013-08-20T02:29:00.273"
        Name = "RafaelM"
    />    
    <row
        ClientCode = "260"
        Date = "2015-07-21T00:00:59:001"
        Name = "MichelangeloX"
    />
</NewDataSet>

$xml in your code represents the root element of your XML, <row> is its child. Therefore, the path is $xml->row:

$xml = simplexml_load_string($x); // assume XML in $x

foreach ($xml->row as $row) {

    $id = $row["ClientCode"];
    $created = $row["Date"];
    $name = $row["Name"];

    echo "client $name with the id $id has been created on $created." . PHP_EOL;

}

see a working example here: https://eval.in/402313

Upvotes: 1

Related Questions