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

Question:

Good afternoon,

Next, I have a system that already has the ids registered in a table, (cars are optional for cars) and in the other table where the cars are registered, these IDS already registered are called, the system only reads in the database of the table vehicles the ids registered in the optional field…example in the table is registered like this

optional and below: 1,24,45,57.54

The ids are registered and registered according to what the user needs, in this case, as I'm getting it from the xml LOGO below, I'll show you…

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 values ​​separated only by "," to insert in the column.. Below the Options 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>

Just Some Optionals as an example.

would you be able to help me?

Answer:

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

Scroll to Top
AllEscort