Foreach in XML with ids and store in a variable to insert data in a given table

Asked

Viewed 347 times

3

Good afternoon,

Next, I have a system that already have the registered ids in a table, ( of cars , are opicional of cars) and in the other table where it is registered the cars is called these IDS already registered, the system only reads in the database of the table vehicles the ids registered in the optional field...example in the table is registered so

optional and bottom : 1,24,45,57,54

The ids are registered and registered according to what the user needs, in this case as I am picking up the xml SOON below I will show..

I need to take the XML IDS and put them in the column separated by , and for that I will need to use a foreach.. and store the values separated only by "," to insert into the column.. Below the Optional XML

<opcionais>
<opcional id="54">Air bag</opcional>
<opcional id="4">Alarme</opcional>
<opcional id="6">Ar condicionado</opcional>
<opcional id="40">Volante com regulagem de altura</opcional>
<opcional id="57">Volante em couro</opcional>
<opcional id="56">Volante espumado</opcional>
</opcionais>

Some Options as an example.

would be able to help me?

1 answer

1


You can test :

<?php
$xml = <<<XML
<?xml version="1.0" encoding="utf-8"?>
<opcionais>
    <opcional id="54">Air bag</opcional>
    <opcional id="4">Alarme</opcional>
    <opcional id="6">Ar condicionado</opcional>
    <opcional id="40">Volante com regulagem de altura</opcional>
    <opcional id="57">Volante em couro</opcional>
    <opcional id="56">Volante espumado</opcional>
</opcionais>
XML;
$sxml = new SimpleXMLElement($xml);
$ids = array();
foreach($sxml->children() as $opcional)
{ 
    echo $opcional['id'];
    $ids[] = $opcional['id'];
}
$idsBd = implode(',', $ids);

include 'connect.php';
$sql = "INSERT INTO sua_tabela (sua_coluna) VALUES ('$idsBD')";     
if ($con->query($sql) === TRUE)
{
    echo "realizado!!!!!!!!!!!!!!!";
}
else
{
    echo "Error: " . $sql . "<br>" . $con->error;
}
?>

Checks your connection variables and etc...

Recommended reading Simplexml

  • No, first of all, it was what I needed, worth just making a change in the code...

  • #################################### INSERT OPTIONS ########################################################################################################################################################### { echo $optional['id']; $ids[] = $optional['id']; } $opc2 = implode(',', $ids); ################################################## ########################################################################

  • 1

    If any of the answers is valid, you could validate it by clicking on the green icon below the evaluation arrows... ;)

  • Thanks, you’ve helped a lot!

Browser other questions tagged

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