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

3

Good afternoon,

Next, I have a system that already has the ids registered in a table, (of cars, are optional of cars) and in the other table where is registered the cars calls these IDS already registered, the system only le in the bank of data of the table vehicles the ids registered in the optional field ... example in the table is registered thus

optional and below: 1.24,45,57.54

The ids are registered and registered according to what the user needs, in this case how I am getting the xml LOGO below will show ..

I need to get the XML IDS and put them inserted in the column separated by, and for that if I'm not mistaken I'll need to use a foreach .. and store the separated values only by "," to insert in the column .. Below the XML of the Options

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

So there are some options as an example.

Would you help me?

    
asked by anonymous 07.11.2016 / 18:06

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;
}
?>

Check your connection variables and etc ...

Recommended reading SimpleXML

    
07.11.2016 / 19:13