Chủ đề này được thoát ra từ lâu, nhưng tôi chỉ tìm thấy nó. Cảm ơn Chúa.
Vấn đề của tôi là tôi phải đọc tệp ONIX (dữ liệu sách) và lưu trữ nó vào cơ sở dữ liệu của chúng tôi. Tôi sử dụng simplexml_load trước đây, và mặc dù nó sử dụng rất nhiều bộ nhớ nhưng vẫn ok cho tập tin tương đối nhỏ (lên đến 300MB). Ngoài kích thước đó là một thảm họa đối với tôi.
Sau khi đọc, đặc biệt là diễn giải của Francis Lewis, tôi sử dụng kết hợp xmlreader và simplexml. Kết quả là đặc biệt, sử dụng bộ nhớ nhỏ và chèn nó vào cơ sở dữ liệu đủ nhanh cho tôi.
Đây là mã của tôi:
<?php
$dbhost = "localhost"; // mysql host
$dbuser = ""; //mysql username
$dbpw = ""; // mysql user password
$db = ""; // mysql database name
//i need to truncate the old data first
$conn2 = mysql_connect($dbhost, $dbuser, $dbpw);
mysql_select_db($db);
mysql_query ("truncate ebiblio",$conn2);
//$xmlFile = $_POST['xmlFile'];
//$xml=simplexml_load_file("ebiblio.xml") or die("Error: Cannot create object");
$reader = new XMLReader();
//load the selected XML file to the DOM
if (!$reader->open("ebiblio.xml")) {
die("Failed to open 'ebiblio.xml'");
}
while ($reader->read()):
if ($reader->nodeType == XMLReader::ELEMENT && $reader->name == 'product'){
$xml = simplexml_load_string($reader->readOuterXML());
$productcode = (string)$xml->a001;
$title = (string)$xml->title->b203;
$author = (string)$xml->contributor->b037;
$language = (string)$xml->language->b252;
$category = $xml->subject->b069;
$description = (string)$xml->othertext->d104;
$publisher = (string)$xml->publisher->b081;
$pricecover = (string)$xml->supplydetail->price->j151;
$salesright = (string)$xml->salesrights->b090;
@$productcode1 = htmlentities($productcode,ENT_QUOTES,'latin1_swedish_ci');
@$title1 = htmlentities($title,ENT_QUOTES,'latin1_swedish_ci');
@$author1 = htmlentities($author,ENT_QUOTES,'latin1_swedish_ci');
@$language1 = htmlentities($language,ENT_QUOTES,'latin1_swedish_ci');
@$category1 = htmlentities($category,ENT_QUOTES,'latin1_swedish_ci');
@$description1 = htmlentities($description,ENT_QUOTES,'latin1_swedish_ci');
@$publisher1 = htmlentities($publisher,ENT_QUOTES,'latin1_swedish_ci');
@$pricecover1 = htmlentities($pricecover,ENT_QUOTES,'latin1_swedish_ci');
@$salesright1 = htmlentities($salesright,ENT_QUOTES,'latin1_swedish_ci');
$conn = mysql_connect($dbhost, $dbuser, $dbpw);
mysql_select_db($db);
$sql = "INSERT INTO ebiblio VALUES ('" . $productcode1 . "','" . $title1 . "','" . $author1 . "','" . $language1 . "','" . $category1 . "','" . $description1 . "','" . $publisher1 . "','" . $pricecover1 . "','" . $salesright1 . "')";
mysql_query($sql, $conn);
$reader->next('product');
}
endwhile;
?>
Bạn đã đọc một số người sử dụng đã góp phần ví dụ trong tài liệu PHP? http://www.php.net/manual/en/class.xmlreader.php#61929 có thể hữu ích. – mcrumley