[英]Need some help with XML parsing
XML提要位於: http : //xml.betclick.com/odds_fr.xml
我需要一個php循環來回顯比賽的名稱,小時,下注選項和賠率鏈接。 該功能將只選擇並顯示當天帶有流=“ 1”且下注類型為“ Ftb_Mr3”的比賽。
我是xpath和simplexml的新手。
提前致謝。
到目前為止,我有:
<?php
$xml_str = file_get_contents("http://xml.betclick.com/odds_fr.xml");
$xml = simplexml_load_string($xml_str);
// need xpath magic
$xml->xpath();
// display
?>
一旦掌握了Xpath,它就非常簡單
您基本上希望獲得具有特定屬性的每個匹配標簽
//match[@streaming=1]
會正常工作,它會從父標簽下面獲取每個匹配標簽,並且屬性流等於1
而且我剛剛意識到,您也想要匹配類型為“ Ftb_Mr3”的比賽
//match[@streaming=1]/bets/bet[@code="Ftb_Mr3"]
但是,這將返回下注節點,我們需要比賽,我們知道這是祖父母
//match[@streaming=1]/bets/bet[@code="Ftb_Mr3"]/../..
這兩個點的工作方式與在文件路徑中一樣,並獲得了匹配。
現在將其應用於您的樣本中,只需將最后一位更改為
// need xpath magic
$nodes = $xml->xpath('//match[@streaming=1]/bets/bet[@code="Ftb_Mr3"]/../..');
foreach($nodes as $node) {
echo $node['name'].'<br/>';
}
打印所有匹配名稱。
我真的不知道如何使用xpath,但是如果您想“循環”它,這應該可以幫助您入門:
<?php
$xml = simplexml_load_file("odds_fr.xml");
foreach ($xml->children() as $child)
{
foreach ($child->children() as $child2)
{
foreach ($child2->children() as $child3)
{
foreach($child3->attributes() as $a => $b)
{
echo $a,'="',$b,"\"</br>";
}
}
}
}
?>
這將使您進入具有“ streaming”屬性的“ match”標簽。 我也不知道什么是“每日比賽”,但是...
基本上完全符合w3c參考: http : //www.w3schools.com/PHP/php_ref_simplexml.asp
我在一個項目上使用它。 通過以下方式刮掉Beclic賠率:
<?php
$match_csv = fopen('matches.csv', 'w');
$bet_csv = fopen('bets.csv', 'w');
$xml = simplexml_load_file('http://xml.cdn.betclic.com/odds_en.xml');
$bookmaker = 'Betclick';
foreach ($xml as $sport) {
$sport_name = $sport->attributes()->name;
foreach ($sport as $event) {
$event_name = $event->attributes()->name;
foreach ($event as $match) {
$match_name = $match->attributes()->name;
$match_id = $match->attributes()->id;
$match_start_date_str = str_replace('T', ' ', $match->attributes()->start_date);
$match_start_date = strtotime($match_start_date_str);
if (!empty($match->attributes()->live_id)) {
$match_is_live = 1;
} else {
$match_is_live = 0;
}
if ($match->attributes()->streaming == 1) {
$match_is_running = 1;
} else {
$match_is_running = 0;
}
$match_row = $match_id . ',' . $bookmaker . ',' . $sport_name . ',' . $event_name . ',' . $match_name . ',' . $match_start_date . ',' . $match_is_live . ',' . $match_is_running;
fputcsv($match_csv, explode(',', $match_row));
foreach ($match as $bets) {
foreach ($bets as $bet) {
$bet_name = $bet->attributes()->name;
foreach ($bet as $choice) {
// team numbers are surrounded by %, we strip them
$choice_name = str_replace('%', '', $choice->attributes()->name);
// get the float value of odss
$odd = (float)$choice->attributes()->odd;
// concat the row to be put to csv file
$bet_row = $match_id . ',' . $bet_name . ',' . $choice_name . ',' . $odd;
fputcsv($bet_csv, explode(',', $bet_row));
}
}
}
}
}
}
fclose($match_csv);
fclose($bet_csv);
?>
然后將csv文件加載到mysql中。 每分鍾運行一次,到目前為止效果很好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.