<?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");php
因爲我的水平有限,調試花了一個多小時,但願看到這Blog的人半個小時調試出來。html
<?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); ?>