我这里有XML http://xml.tab.co.nz/odds/2017-02-08 我想检索号码'来自会议节点的属性,'数字'来自种族节点的属性和' win'来自入口节点的属性。 他们应该依赖提取手段 会议2比赛1然后所有赢得它的属性。 会议2比赛2然后所有赢得它的属性。 等等。 我试过这个
$xmlDoc = new DOMDocument();
$xmlDoc->load( 'http://xml.tab.co.nz/odds/2017-02-08' );
$searchNode2 = $xmlDoc->getElementsByTagName( "meeting" );
foreach( $searchNode2 as $searchNode2 )
{
$valueID2 = $searchNode2->getAttribute('number');
$meetings[$k]=$valueID2;
$k++;
//echo "$valueID2\n";
}
$searchNode1 = $xmlDoc->getElementsByTagName( "race" );
foreach( $searchNode1 as $searchNode1 )
{
$valueID1 = $searchNode1->getAttribute('number');
$races[$j]=$valueID1;
$j++;
//echo "$valueID1\n";
}
$searchNode = $xmlDoc->getElementsByTagName( "entry" );
foreach( $searchNode as $searchNode )
{
$valueID = $searchNode->getAttribute('win');
$runners[$i]=$valueID;
$i++;
//echo "$valueID\n";
}
但是每件事都是独立的,无法弄清楚如何做到这一点。
答案 0 :(得分:0)
考虑SimpleXMLElement的XPath,沿着XML的每个树级向下走,将最后编码的两级数组更新为json:
// Loading XML source
$xml = simplexml_load_file('http://xml.tab.co.nz/odds/2017-02-08');
// Initializing variables
$i = 0;
$data = [];
// Extracting values
foreach ($xml->xpath("//meeting") as $mtg){
foreach ($mtg->xpath("races") as $races) {
foreach ($races->xpath("race") as $race) {
foreach ($race->xpath("entries") as $entries) {
foreach ($entries->xpath("entry") as $entry) {
$data[$i]['meeting'] = (string)$mtg->xpath("@number")[0];
$data[$i]['races'] = (string)$race->xpath("@number")[0];
$win = 'win-'.(string)$entry->xpath("@number")[0];
if ($entry->xpath("@win")) {
$data[$i][$win] = (string)$entry->xpath("@win")[0];
} else {
$data[$i][$win] = '';
}
}
$i++;
}
}
}
}
// Encode json and export to external file
$json = json_encode($data, JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
echo $json;
file_put_contents('Output.json", $json);
<强>输出强>
[
{
"meeting": "2",
"races": "1",
"win-1": "8.90",
"win-2": "14.70",
"win-3": "2.80",
"win-4": "54.80",
"win-5": "13.10",
"win-6": "7.10",
"win-7": "13.30",
"win-8": "8.60",
"win-9": "4.40"
},
{
"meeting": "2",
"races": "2",
"win-1": "5.50",
"win-2": "6.10",
"win-3": "6.80",
"win-4": "4.80",
"win-5": "14.70",
"win-6": "4.20",
"win-7": "35.00",
"win-8": "12.40",
"win-9": "28.00",
"win-10": "23.50"
},
{
"meeting": "2",
"races": "3",
"win-1": "8.70",
"win-2": "9.10",
"win-3": "13.70",
"win-4": "1.70",
"win-5": "17.00",
"win-6": "11.70",
"win-7": "5.30",
"win-8": ""
},
...