簡體   English   中英

xml用php和mysql插入

[英]xml insert with php and mysql

假設您在商店中有一個包含80種產品的xml.file。(這將是一個供稿,但我不想混淆這個問題)

80種產品具有許多要素,例如

    <product> 
    <price> millions </price>
    <colour> red </colour>
    <pictures> <pic> picture1_url </pic> <pic> picture2_url </pic> 
 <pic>picture3_url </pic>
 </pictures>
    </product >

您的客戶希望在網頁/應用程序上使用.xml,他的客戶可以在其中使用搜索表單按價格和顏色搜索數據,並查看嵌套在主要元素“產品”中的“許多”圖片。

我的問題是:我是否應該將數據保存在關系表中每個元素的列中(關系,因為有很多圖片,我認為需要將這些圖片外鍵化為產品ID。

我已經能夠使用dom / simple_xml來回顯頁面上的產品,而無需數據庫,但是我有na的感覺,我應該將數據放入db中,以便使用mysql select語句更輕松地進行查詢。

我什至與開發人員交談,並在wordpress meta表上看到圖片的url保持逗號分隔在一個表中。 我認為這在db領域是非常糟糕的做法?

麻煩的是,當我還有許多其他圖片要與該ID關聯時,很難將外鍵附加到1 ID。.(當foreach /循環產品時,獲取最后一個ID似乎感到困惑。

這是我的代碼,但是如果我決定走dom路由並且不需要將數據放在dbase中,我想它就沒用了。

 $xml = simplexml_load_file('products.xml') or die("can not find it");

        foreach($xml->product as $row){ 


         $price  =   $row->price
        $colour  =$row->colour
        $pictures =  $row->pictures 

        $sql= insert into products table 

}

妳去

CREATE TABLE products (id INT NOT NULL PRIMARY KEY auto_increment, colour VARCHAR(25), price DECIMAL)

請注意,價格為小數-通常將價格保留為小數

CREATE TABLE pictures (id INT NOT NULL PRIMARY KEY auto_increment, picture_url VARCHAR(100))

CREATE TABLE relations (product_id INT, picture_id INT)

插入值...

INSERT INTO products VALUES (NULL, 'red', 100500.00)
INSERT INTO pictures VALUES (NULL, 'picture_url1');
INSERT INTO pictures VALUES (NULL, 'picture_url2');
INSERT INTO pictures VALUES (NULL, 'picture_url3');

添加關系

INSERT INTO relations VALUES (1, 1);
INSERT INTO relations VALUES (1, 2);
INSERT INTO relations VALUES (1, 3);

最后-獲得結果

SELECT price, colour, group_concat(pictures.picture_url) as 'pictures' FROM products, relations, pictures WHERE products.id = 1 AND
relations.product_id=products.id AND relations.picture_id=pictures.id

------------------------------------------------------
|price |colour|pictures                              |
------------------------------------------------------
|100500|red   |picture_url1,picture_url2,picture_url3|
------------------------------------------------------

更新。 使用SimpleXML插入所有圖片

$new_xml = new SimpleXMLElement($xml_file);

foreach ($new_xml->product->pictures->pic as $pic) {
//this is your picture url
   $your_picture_url = $pic;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM