2012-01-03 142 views
1

我收到優惠提要並希望對其進行處理,以便將其添加到我的數據庫中。下面是它在未來的格式:如何將XML Feed中的數據添加到MySQL數據庫

<deals> 
<item> 
    <couponid>int</couponid> 
    <merchantid>int</merchantid> 
    <merchantname>string</merchantname> 
    <network>string</network> 
    <label>string</label> 
    <restrictions>string</restrictions> 
    <couponcode>string</couponcode> 
    <link>string</link> 
    <directlink>string</directlink> 
    <startdate>YYYY-MM-DD HH:MM TMZ</startdate> 
    <enddate>YYYY-MM-DD HH:MM TMZ</enddate> 
    <image>string</image> 
    <dealtypes> 
    <type>string</type> 
    </dealtypes> 
    <categories> 
    <category>string</category> 
    </categories> 
    <status>status</status> 
    <lastupdated>YYYY-MM-DD HH:MM TMZ</lastupdated> 
    <errorreporturl>string</errorreporturl> 
    <changeaudit>string</changeaudit> 
    <price>string</price> 
    <listprice>string</listprice> 
    <discount>string</discount> 
    <percent>string</percent> 
    <local> 
    <city>string</city> 
    <state>string</state> 
    <zipcode>string</zipcode> 
    <address>string</address> 
    <businessname>string</businessname> 
    <businessurl>string</businessurl> 
    <title2>string</title2> 
    <expirationdate>string</expirationdate> 
    <minpurchase>int</minpurchase> 
    <maxpurchase>int</maxpurchase> 
    <limitedqty>bool</limitedqty> 
    <region>string</region> 
    </local> 
</item> 
</deals> 

我可以使用處理大部分物品:

'couponid' => $node->getElementsByTagName('couponid')->item(0)->nodeValue 

但是,我怎麼處理這些「本地」節點內的項目。並非Feed中的所有項目都有此「本地」節點。我將如何處理它?將這項工作:

$localData = $node->getElementsByTagName('local')->item(0); 
if $localData { 
'city' => $node->getElementsByTagName('local')->item(city)->nodeValue; 
'state' => $node->getElementsByTagName('local')->item(state)->nodeValue; 
etc.. 
} 
+0

你說過「這會工作嗎」,它工作嗎? 無論如何,也許'$ node-> getElementsByTagName('local') - > getElementsByTagName('city') - > nodeValue'將起作用。 – Dion 2012-01-04 00:03:25

回答

1

DOMNodeListdocsDOMNodeList::item將返回

節點在的DOMNodeList第index位置如果 不是有效索引,則爲NULL。

所以,不,你不能做$node->getElementsByTagName('local')->item(city)

當你做到這一點$localData = $node->getElementsByTagName('local')->item(0);$localData變量設置爲一個DOMNode對象,他們的孩子,那麼你可以訪問像任何其他DOMNode對象的子女。

然而

如果你只是簡單的讀取XML,而不是寫/追加,PHP的SimpleXML是更易於使用(因此得名),比DOM,我會推薦它在你的情況:

$deals = new SimpleXMLElement($my_xml); 

$city = $deals->item->local->city[0]; 
$state = (string) $deals->item->local->state; 

echo "city: $city\n"; 
echo "state: $state\n"; 

注意,使用(string)鑄造方法得到相同的結果簡單地引用該元素的[0]鍵。

+0

原始提要解析腳本由提要所有者提供。不知道他們爲什麼不使用SimpleXML。我正在編寫的新腳本基於您給我的代碼。非常感謝! – PaperChase 2012-01-05 00:09:40

0

在PHP中,你可以做到以下幾點:

- >獲取XML文件:

$myXMLString = file_get_contents($url); 
$doc = new DOMDocument('1.0', 'iso-8859-1'); 
$doc->loadXML($myXMLString); 
$deals = $doc->getElementsByTagName("item"); 

foreach($deals as $item){ 
    functionDeals($item); 
} 

然後在功能 「functionDeals」 提取子元素以同樣的方式。 否則esiest的方法是使用Hibernate(Java):點擊此鏈接http://javaboutique.internet.com/tutorials/mapping/

希望這有助於