Search code examples
phpsimplexml

Parse simplexml into MYSQL


I have an api, which I send to a database and the results are returned in an xml format, this works fine and i can output the results to the screen with no problem. The xml feed is along list of property details. What i am trying to do is store the results in a mysql database, using the code below.

  $feeds = array('http://web.demo.net/ademo_search.xml?  &upw=123456');
 foreach( $feeds as $feed ) {
$xml = simplexml_load_file($feed);

foreach($xml->channel->item as $item)
{

mysql_query("INSERT INTO property1 (id, department, branch, address1) 
VALUES (
    '', 
    '".mysql_real_escape_string($item->id)."', 
    '".mysql_real_escape_string($item->department)."', 
    '".mysql_real_escape_string($item->branch)."', 
    '".mysql_real_escape_string($item->address1)."')");       
     }
  }

When I run this code I don't get an errors, nor does the data get added to the database.

here is a link to the xml structure, as you will see for my test i am only trying to insert the first few items.


Solution

  • This is exactly what you need :)

    I hope you like it

    $feed = "test.xml";
    $xml = simplexml_load_file($feed);
    
    $arr = array();
    $i = 0;
    foreach($xml->houses->property as $item){
        $arr[$i][] = (string) $item->id;
        $arr[$i][] = (string) $item->department;
        $arr[$i][] = (string) $item->branch;
        $arr[$i][] = (string) $item->address->address1;
        $i++;
    }
    var_dump($arr); // now you have them in an array .. store them in db ;)