您可以使用SimpleXML、 XPath 和 for-each 循环非常轻松地做到这一点。
对于 SimpleXML 对象,只需记住以下几点:
- 每个元素变成一个
SimpleXMLElement
SimpleXMLElement
使用数组表示法访问 a 的属性(例如, Element['attributeName']
)
- 使用对象表示法访问特定名称的子元素(例如,
Element->ChildElements
或Element->{Child-Element-With-Strange-Name}
)
- 始终转换为字符串以获取文本值(例如
(string) Element
or (string) Element['attribute']
)
- 对于更高级的查询,请使用该
xpath
方法。
- 要访问命名空间元素,请使用
children
方法的第一个参数。
通常,只要您拥有中等大小的数据结构化(相对于文档结构化)XML,阻力最小的路径就是SimpleXML
. 如果您有一个非常大的文档,请使用组合XMLReader
将文档分成块,并XMLReader::expand()
使用DOMDocument
或处理这些块SimpleXML
。
以下函数会将您想要的数据提取到结构化数组中:
function extractDataFromFeed($feeduri) {
$events = array();
$sxe = simplexml_load_file($feeduri);
$targetMasterEvents = $sxe->xpath('/EventData/MasterEvents[starts-with(./@TopLevelName, "NRL Round ")]');
foreach ($targetMasterEvents as $targetMasterEvent) {
foreach ($targetMasterEvent->Event as $targetEvent) {
$event = array(
'EventUrl' => (string) $targetEvent['EventURL'],
'Competitors' => array(), // CompetitorName => StraightBetPrice,
// (assumes 1 price per competitorname)
);
foreach ($targetEvent->Competitors as $targetCompetitor) {
$targetBets = $targetCompetitor->xpath('BetType[@BetTypeName="Straight Bet"]');
foreach ($targetBets as $targetBet) {
$event['Competitors'][(string) $targetCompetitor['CompetitorName']]
= (string) $targetBet['Price'];
}
}
}
$events[] = $event;
}
return $events;
}
$FEED = 'http://xmlfeeds.centrebet.com/xmlRugbyLeaguefeed.xml';
$events = extractDataFromFeed($FEED);
var_export($events);
从这里将这些数据插入数据库是一件简单的事情(下面的代码未经测试):
function insertEvents($eventname, $events, PDO $pdo) {
// Set exception mode (if not set already)
$old_ERRMODE = $pdo->getAttribute(PDO::ATTR_ERRMODE);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// create prepared statements
$insertEvent = $pdo->prepare('INSERT INTO events (EventName, EventURL) VALUES (?,?)');
$insertBet = $pdo->prepare('INSERT INTO bets (event_id, CompetitorName, Price) VALUES (?,?,?)');
// bind statement parameters
$insertEvent->bindValue(1, $eventName, PDO::PARAM_STR);
$insertEvent->bindParam(2, $eventURL, PDO::PARAM_STR);
$insertBet->bindParam(1, $event_id, PDO::PARAM_INT);
$insertBet->bindParam(2, $competitorName, PDO::PARAM_STR);
$insertBet->bindParam(3, $price);
// loop through event array, executing inserts
foreach($events as $event) {
$eventUrl = $event['EventURL'];
$insertEvent->execute();
$event_id = $pdo->lastInsertId();
foreach($event['Competitors'] as $competitorName => $price) {
$insertBet->execute();
}
}
// restore ERRMODE setting (won't be restored if exception is raised!)
$pdo->setAttribute(PDO::ATTR_ERRMODE, $old_ERRMODE);
}