How to import photos from an XML with PHP

0

I'm trying to import an XML file, but I do not know how to import it when it has a field inside another field, see below the example that explains better:

<imovel>
  <id>1</id>
  <endereco>abc</endereco>
  <fotos>
    <foto>
      <arquivo>foto1.jpg</arquivo>
    </foto>
    <foto>
      <arquivo>foto2.jpg</arquivo>
    </foto>
  </fotos>
</imovel>
<imovel>
  <id>2</id>
  <endereco>rua X</endereco>
  <fotos>
    <foto>
      <arquivo>foto5.jpg</arquivo>
    </foto>
    <foto>
      <arquivo>foto7.jpg</arquivo>
    </foto>
  </fotos>
</imovel>

For the "common" first level fields, I usually import the following code:

$xml = 'arquivo.xml';
$xml = new SimpleXMLElement($xml,NULL,true);
foreach ($xml->children() as $row) {
    $id = $row->id;
    $endereco = $row->endereco;  
}

Then I'll insert it into my database.

$sql = "INSERT INTO tabela (id,endereco) VALUES ('{$id}','{$endereco}')

Once you get the photos, it should be inserted into the photos table, where imd is the id of the property:

$sql = "INSERT INTO tabelafotos (imid,foto) VALUES {$fotoarquivos}

I tried the following, but it did not work:

$xml = 'arquivo.xml';
$xml = new SimpleXMLElement($xml,NULL,true);
foreach ($xml->children() as $row) {
    $id = $row->id;
    $endereco = $row->endereco;
    $fotos = $row->fotos;
    foreach ($fotos->children() as $foto) {
      $fotoarquivo = $foto->arquivo;
      $fotoarquivos.="('".$id."','".$fotoarquivo'),"; 
    }
}$fotoarquivos=substr($fotoarquivos,0,-1);
    
asked by anonymous 07.11.2018 / 17:53

1 answer

0
  

In xml the root tag is missing.

<raiz>
  <imovel>
    <id>1</id>
     .....
     .....
  </imovel>
  <imovel>
    <id>1</id>
     .....
     .....
  </imovel>
</raiz>
  

wrong syntax $fotoarquivos.="('".$id."','".$fotoarquivo'),";

Example 1

  

You need to enter all levels of the structure, see

$xml = simplexml_load_file("arquivo.xml");

foreach ($xml as $imovel):
    $id = $imovel->id;
    foreach($imovel->fotos as $items):
            foreach($items->foto as $foto):
                 $fotoarquivos.="('".$id."','".trim($foto->arquivo)."'),";
            endforeach;
        endforeach;
endforeach;

$fotoarquivos=substr($fotoarquivos,0,-1);

echo $fotoarquivos;

Example 2

  

A foreach loop around the root elements and then an XPath query to facilitate access to the inner elements.

     

It's still quite hacky with two foreach loops, but it works fine.

$xml = simplexml_load_file("arquivo.xml");

foreach ($xml as $imovel) {
    $id =  $imovel->id;
    $arquivos = $imovel->xpath("fotos/foto/arquivo");
    foreach ($arquivos as $ar) {
        $fotoarquivos.="('".$id."','".$ar."'),";
    }
}

$fotoarquivos=substr($fotoarquivos,0,-1);

echo $fotoarquivos;
    
07.11.2018 / 23:57