PHP 利用simplexml_load_file 读取XML对应的字段 然后存入mysql数据库

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <news id="1" year="2015">
        <title>海口观澜湖华谊冯小刚电影公社南洋街盛大开街</title>
        <thumbnail>/news/2015/news-12-23_2.jpg</thumbnail>
        <images>
            <image>
                <source>/news/2015/news-12-23.jpg</source>
            </image>
            <image>
                <source>/news/2015/news-12-23_2.jpg</source>
            </image>
            <image>
                <source>/news/2015/news-12-23_3.jpg</source>
            </image>
            <image>
                <source>/news/2015/news-12-23_1.jpg</source>
            </image>
            <image>
                <source>/news/2015/news-12-23_4.jpg</source>
            </image>
        </images>

    </news>
    <news id="2" year="2015">
        <title>万圣节游玩攻略:深入观澜湖  变身“整鬼专家”</title>
        <thumbnail>/news/2015/1.png</thumbnail>
        <images>
            <image>
                <source>/news/2015/1.1.jpg</source>
            </image>
            <image>
                <source>/news/2015/1.2.png</source>
            </image>
            <image>
                <source>/news/2015/1.3.jpg</source>
            </image>
            <image>
                <source>/news/2015/1.4.jpg</source>
            </image>
            <image>
                <source>/news/2015/1.5.jpg</source>
            </image>
            <image>
                <source>/news/2015/1.6.jpg</source>
            </image>
            <image>
                <source>/news/2015/1.7.jpg</source>
            </image>
            <image>
                <source>/news/2015/1.8.png</source>
            </image>

        </images>
    </news>

</root>

 总体的思路是利用print_r 进行打印调试,遇到object就用->读取,遇到Array就用[]读取,在调试的时候遇到中文编码的问题用header("Content-Type: text/html; charset=UTF-8");

由于个人水平有限,调试花了一个多小时,希望看到这Blog的人半个小时调试出来。

<?php

$con = mysql_connect("localhost","dbuser","dbpassword");
if (!$con){
  die('Could not connect: ' . mysql_error());
}else{
  echo 'ok';
}
mysql_select_db("dbname", $con);

//必须要转为utf8否则读入数据库报错,注意与UTF-8的区别
mysql_query('set names utf8;');

$xml=simplexml_load_file("zh-cn/news.xml") or die("Error: Cannot create object");

//页面显示
header("Content-Type: text/html; charset=UTF-8");
foreach ($xml as $news) {
   $id = (string)$news['id'];

   $year = (string)$news['year'];

   $title =(string)$news->title;

   $thumbnail = (string)$news->thumbnail;
   $content = (string)$news->content;

//看到这段代码的同学也可以研究一下VALUES中的变量$title,$thumbnail,$content必须要加‘’,如果没有加的话就无法insert   

mysql_query("INSERT INTO news (newsid, year,title,thumbnail,content) VALUES ($id, $year,'$title','$thumbnail','$content')")or die(mysql_error());

   foreach ($news->images->image as $image) {
        $image = (string)$image->source;
        mysql_query("INSERT INTO sub_news (news_id, image) VALUES ($id, '$image')")or die(mysql_error());
   }
}
mysql_close($con);
?>

 

 

posted @ 2016-04-22 15:03  Nick_Cai  阅读(1991)  评论(0编辑  收藏  举报