Format xml in php to write to Mysql?

Asked

Viewed 212 times

0

I need to format a xml in php to record on MySQL, but I’m having a hard time understanding it and even doing it. Today I have this xml:

<?xml version='1.0' encoding='UTF-8'?>      
    <api>
       <response version='1.1.3' success='1'
                 message='Previs&amp;#xE3;o de chuva - mm'
                 type='chuva' time='1491420459' total='1'>
          <legends />
       </response>
       <data>
          <item dateBegin='2017-04-05 00:00:00' dateEnd='2017-04-19 23:59:59'>
             <locale id='6634' name='NomeCidade'
                               latitude='-23.7060'
                               longitude='-51.6390'>
                <type id='7' name='CIDADE' />
             </locale>
             <weather>
                <item probability='80' precipitation='10' date='2017-04-05 00:00:00' />
                <item probability=''   precipitation='20' date='2017-04-06 00:00:00' />
                <item probability='80' precipitation='6'  date='2017-04-07 00:00:00' />
                <item probability='80' precipitation='2'  date='2017-04-08 00:00:00' />
                <item probability='80' precipitation='4'  date='2017-04-09 00:00:00' />
                <item probability='80' precipitation='5'  date='2017-04-10 00:00:00' />
                <item probability='0'  precipitation='0'  date='2017-04-11 00:00:00' />
                <item probability='0'  precipitation='0'  date='2017-04-12 00:00:00' />
                <item probability='0'  precipitation='0'  date='2017-04-13 00:00:00' />
                <item probability='0'  precipitation='0'  date='2017-04-14 00:00:00' />
                <item probability='0'  precipitation='0'  date='2017-04-15 00:00:00' />
                <item probability='0'  precipitation='0'  date='2017-04-16 00:00:00' />
                <item probability='0'  precipitation='0'  date='2017-04-17 00:00:00' />
                <item probability='80' precipitation='0'  date='2017-04-18 00:00:00' />
                <item probability='0'  precipitation='0'  date='2017-04-19 00:00:00' />
             </weather>
          </item>
       </data>
    </api>

And what I’m trying to do is something like this:

if ($status = true) 
{
    //Leitura do ramo Cidade
    for($i=0; $i < count($xml->cidades->cidade); $i++) 
    {
        $id   = $xml->cidades->cidade[$i]['id'];
        //Leitura do ramo Data e seus atributos
        for($z=0; $z < count($xml->cidades->cidade[$i]->data); $z++) 
        {
            $data = $xml->cidades->cidade[$i]->data[$z]['diaprevisao']; 
            $data_aux  = substr($data,6,4).'-'.substr($data,3,2).'-'.substr($data,0,2);

            //atributos da data
            $frase   = utf8_decode($xml->cidades->cidade[$i]->data[$z]->frase);
            $min       = utf8_decode($xml->cidades->cidade[$i]->data[$z]->min);
            $max       = utf8_decode($xml->cidades->cidade[$i]->data[$z]->max);
            $prob     = utf8_decode($xml->cidades->cidade[$i]->data[$z]->prob);
            $prec     = utf8_decode($xml->cidades->cidade[$i]->data[$z]->prec);
            $icomanha  = utf8_decode($xml->cidades->cidade[$i]->data[$z]->icomanha);
            $icotarde  = utf8_decode($xml->cidades->cidade[$i]->data[$z]->icotarde);
            $iconoite  = utf8_decode($xml->cidades->cidade[$i]->data[$z]->iconoite);
            $icodia     = utf8_decode($xml->cidades->cidade[$i]->data[$z]->icondia);
            $uv         = utf8_decode($xml->cidades->cidade[$i]->data[$z]->uv);
            $ventodir  = utf8_decode($xml->cidades->cidade[$i]->data[$z]->ventodir);
            $ventomax  = utf8_decode($xml->cidades->cidade[$i]->data[$z]->ventomax);
            $ventoint  = utf8_decode($xml->cidades->cidade[$i]->data[$z]->ventoint);
            $umidade   = utf8_decode($xml->cidades->cidade[$i]->data[$z]->umidade);

            mysql_select_db($database_con, $conn);
            $sql = "SELECT Data, IdCidade FROM PrevisaoClima WHERE Data = '$data_aux' AND IdCidade = $id";
            $rcDados = mysql_query($sql, $conn) or die(mysql_error());
            $row_rcDados = mysql_fetch_assoc($rcDados);
            $totalRows_rcDados = mysql_num_rows($rcDados);

            if ($totalRows_rcDados > 0) {

                mysql_select_db($database_con, $conn);
                $sql = "UPDATE `clima`.`PrevisaoClima` SET `Frase`='$frase', `TempMin`='$min', `TempMax`='$max', `ProbChuva`='$prob', `PrecisaoChuva`='$prec', `IconeManha`='$icomanha', `IconeTarde`='$icotarde', `IconeNoite`='$iconoite', `IconeDia`='$icodia', `VentoDir`='$ventodir', `VentoMax`='$ventomax', `VentoMin`='$ventoint', `Umidade`='$umidade', `Uv`='$uv' WHERE `Data`='$data_aux' AND `IdCidade`=$id";
                $result = mysql_query($sql, $conn);
                if (!$result) {
                    $message  = 'ERRO: ' . mysql_error() . "\n";
                    $message .= 'Query: ' . $sql;
                    die($message);
                }
            } else {

                mysql_select_db($database_con, $conn);
                $sql = "INSERT INTO `clima`.`PrevisaoClima` (`Data`, `IdCidade`, `Frase`, `TempMin`, `TempMax`, `ProbChuva`, `PrecisaoChuva`, `IconeManha`, `IconeTarde`, `IconeNoite`, `IconeDia`, `VentoDir`, `VentoMax`, `VentoMin`, `Umidade`, `Uv`) VALUES ('$data_aux', '$id', '$frase', '$min', '$max', '$prob', '$prec', '$icomanha', '$icotarde', '$iconoite', '$icodia', '$ventodir', '$ventomax', '$ventoint', '$umidade', '$uv')";
                $result = mysql_query($sql, $conn);
                if (!$result) {
                    $message  = 'ERRO: ' . mysql_error() . "\n";
                    $message .= 'Query: ' . $sql;
                    die($message);
                }
            }
        }
    }
}
echo "Importação terminada.";

Putting nodes in variables php.

  • you’re using simple xml?

  • Hello @Rafaelacioly, I’m using file_get_contents

  • 1

    I understood that its greatest difficulty was to access the positions, I made an answer in this sense, if you have any more questions, we are there ... Item 3 is easy to understand the process of accessing each item.

1 answer

0


Possible ways:

1)

function xml2array ( $xmlObject, $out = array () )
{
    foreach ( (array) $xmlObject as $index => $node )
        $out[$index] = ( is_object ( $node ) ) ? xml2array ( $node ) : $node;
    return $out;
}

Reference SO-SITEen

2)

$array = json_decode(json_encode((array)$xml), TRUE);

Reference SO-SITEen

3)

<?php

    //$item = simplexml_load_string(file_get_contents($url)) // ou
    $item = simplexml_load_file("item.xml");    

    $data['api']['response']['version'] = (string)$item->response['version'];
    $data['api']['response']['success'] = (string)$item->response['success'];
    $data['api']['response']['message'] = (string)$item->response['message'];
    $data['api']['response']['type']    = (string)$item->response['type'];
    $data['api']['response']['time']    = (string)$item->response['time'];
    $data['api']['response']['total']   = (string)$item->response['total'];


    $data['api']['data']['item']['dateBegin'] = (string)$item->data->item['dateBegin'];
    $data['api']['data']['item']['dateEnd']   = (string)$item->data->item['dateEnd'];   

    $data['api']['data']['item']['locale']['id']        = (string)$item->data->item->locale['id'];
    $data['api']['data']['item']['locale']['name']      = (string)$item->data->item->locale['name'];
    $data['api']['data']['item']['locale']['latitude']  = (string)$item->data->item->locale['latitude'];
    $data['api']['data']['item']['locale']['longitude'] = (string)$item->data->item->locale['longitude'];

    $data['api']['data']['item']['locale']['type']['id']   = (string)$item->data->item->locale->type['id'];
    $data['api']['data']['item']['locale']['type']['name'] = (string)$item->data->item->locale->type['name'];

    foreach($item->data->item->weather->item as $w)
    {   
        $data['api']['data']['item']['weather']['item'][] = array
        (
            'probability' => (string)$w['probability'],
            'precipitation' => (string)$w['precipitation'],
            'date' => (string)$w['date']
        );
    }

    var_dump($data) // resultado em array
    //echo json_encode($data, JSON_PRETTY_PRINT); // resultado em json

In this organized way you can send the information by passing the full path of the keys , or even already pass directly to common variables and send to your table, in your question failed to report this as you are doing this process.

  • Hello @Virgilio Novic, I appreciate the great help, my attempt is to pass the values as variables, have to put an example, already asking a lot? Thanks.

  • @adventistapr has how to edit your question by placing the part of the code that writes in the table?

  • @adventistapr does not have $xml->cidades->cidade in xml you passed, I did upon what is in question? see the part you need is undefined?

  • 1

    Hello @Virgilio Novic, you did correctly, the example is an old file I have here, but your explanation already helped me a lot, garadeço.

Browser other questions tagged

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