Home > Enterprise >  How to select specific data fields from XML and insert into MYSQL
How to select specific data fields from XML and insert into MYSQL

Time:04-28

I have XML data I am trying to insert into a MYSQL table, but it appears I am missing something as I not able to currently insert the data into the database. I am only interested in the "Customer" information. Hopefully someone can show me what I am doing wrong. Below is the XML:

<Root>
    <ResponseStatus>
        <Status>OK</Status>
        <TimeStamp>26.4.2022 23:14:37</TimeStamp>
    </ResponseStatus>
    <Customerlist>
        <Customer>
            <ID>1</ID>
            <Name>John Doe</Name>
            <Code>21</Code>
            <Title>CEO</Title>
        </Customer>
        <Customer>
            <ID>2</ID>
            <Name>Tin Ain</Name>
            <Code>22</Code>
            <Title>CTO</Title>
        </Customer>
        <Customer>
            <ID>3</ID>
            <Name>Stacy Doe</Name>
            <Code>32</Code>
            <Title>Manager</Title>
        </Customer>
       
    </Customerlist>
</Root>

Below is a snippet from my php code:

foreach ($xml->children() as $row) {
    $ID = $row->ID;
    $Name = $row->Name;
    $Code = $row->Code;
    $Title = $row->Title;



    $sql = "INSERT INTO customers_table (ID, Name, Code, Title)
    VALUES ('". $ID . "','" . $Name . "','" . $Code . "','" . $Title . "')";

CodePudding user response:

If you use SimpleXML, which I assume, maybe you forgot the node between <Root> and the <Customer>s <CustomerList>. So your first line would be:

foreach ($xml->CustomerList->children() as $row) {
  • Related