How to import photos from XML with PHP

Asked

Viewed 78 times

0

I am trying to import an XML file, but do not know how to import when there is 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 first level "common" fields, I normally import the code below:

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

Then after that I make an insert in my database.

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

After picking up the photos, it should be inserted in tablephotos, where imd is the id of the immovable:

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

I tried it this way, but it didn’t 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);

1 answer

0

xml missing the root tag.

<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 internal elements.

It is still quite Hacky with two foreach loops, but works well.

$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;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.