如何将XML Feed中的数据添加到MySQL数据库
我收到优惠提要并希望对其进行处理,以便将其添加到我的数据库中。下面是它在未来的格式:如何将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..
}
按DOMNodeList
docs,DOMNodeList::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]
键。
原始提要解析脚本由提要所有者提供。不知道他们为什么不使用SimpleXML。我正在编写的新脚本基于您给我的代码。非常感谢! – PaperChase 2012-01-05 00:09:40
在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/
希望这有助于
你说过“这会工作吗”,它工作吗? 无论如何,也许'$ node-> getElementsByTagName('local') - > getElementsByTagName('city') - > nodeValue'将起作用。 – Dion 2012-01-04 00:03:25