duanma8207
2015-07-21 16:37
浏览 52
已采纳

将simplexml解析为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.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • duancan2539 2015-07-21 18:38
    已采纳

    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 ;)
    
    点赞 打赏 评论
  • dongyiyu882684 2015-07-21 16:42

    first: in the feeds array, there are a few spaces, this might cause a problem parsing the url and return 404 error or something (not sure about that, but check it)

    second: in the query, remove the '' because you have 4 columns with 5 variables passed to them

    third: you might want to see MySQL error by adding or die(mysql_error()) after the query before the semicolon

    fourth: consider replacing mysql with mysqli or PDO

    点赞 打赏 评论

相关推荐 更多相似问题