【问题标题】:Pulling NHL Standings from XML Table with PHP使用 PHP 从 XML 表中提取 NHL 排名
【发布时间】:2014-11-26 23:24:50
【问题描述】:

我正在做一个项目,在该项目中我提取有关 NHL 的各种统计数据并将它们插入到 SQL 表中。目前,我正在进行抓取阶段,并找到了一个我已经实现的 XML 解析器,但我终其一生都无法弄清楚如何从中提取信息。该表可在此处找到 -> http://www.tsn.ca/datafiles/XML/NHL/standings.xml。 解析器应该生成一个多维数组,我只是试图从“信息团队”部分中提取所有统计信息,但我不知道如何从数组中提取这些信息。我将如何拉动蒙特利尔的胜利次数? (仅作为其余统计数据的示例) 这是页面当前的样子 -> http://mattegener.me/school/standings.php 这是代码:

<?php
$strYourXML = "http://www.tsn.ca/datafiles/XML/NHL/standings.xml";
$fh = fopen($strYourXML, 'r');
$dummy = fgets($fh);
$contents = '';
while ($line = fgets($fh)) $contents.=$line;
 fclose($fh);
$objXML = new xml2Array();
$arrOutput = $objXML->parse($contents);
print_r($arrOutput[0]); //This print outs the array.

class xml2Array {

var $arrOutput = array();
var $resParser;
var $strXmlData;

function parse($strInputXML) {

        $this->resParser = xml_parser_create ();
        xml_set_object($this->resParser,$this);
        xml_set_element_handler($this->resParser, "tagOpen", "tagClosed");

        xml_set_character_data_handler($this->resParser, "tagData");

        $this->strXmlData = xml_parse($this->resParser,$strInputXML );
        if(!$this->strXmlData) {
           die(sprintf("XML error: %s at line %d",
        xml_error_string(xml_get_error_code($this->resParser)),
        xml_get_current_line_number($this->resParser)));
        }

        xml_parser_free($this->resParser);

        return $this->arrOutput;
}
function tagOpen($parser, $name, $attrs) {
   $tag=array("name"=>$name,"attrs"=>$attrs); 
   array_push($this->arrOutput,$tag);
}

function tagData($parser, $tagData) {
   if(trim($tagData)) {
        if(isset($this->arrOutput[count($this->arrOutput)-1]['tagData'])) {
            $this->arrOutput[count($this->arrOutput)-1]['tagData'] .= $tagData;
        } 
        else {
            $this->arrOutput[count($this->arrOutput)-1]['tagData'] = $tagData;
        }
   }
}

function tagClosed($parser, $name) {
   $this->arrOutput[count($this->arrOutput)-2]['children'][] = $this->arrOutput[count($this-      >arrOutput)-1];
   array_pop($this->arrOutput);
}
}


 ?>

【问题讨论】:

  • 检查我的编辑答案

标签: php mysql arrays xml parsing


【解决方案1】:

将此搜索功能添加到您的班级并使用此代码

$objXML = new xml2Array();
$arrOutput = $objXML->parse($contents);
//  first param is always 0
//  second is 'children' unless you need info like last updated date
//  third is which statistics category you want for example
// 6 => the array you want that has wins and losses
print_r($arrOutput[0]['children'][6]);
//using the search function if key NAME is Montreal in the whole array 
//result will be montreals array
$search_result = $objXML->search($arrOutput, 'NAME', 'Montreal');
//first param is always 0
//second is key name
echo $search_result[0]['WINS'];

function search($array, $key, $value)
{
    $results = array();

    if (is_array($array))
    {
        if (isset($array[$key]) && $array[$key] == $value)
            $results[] = $array;

        foreach ($array as $subarray)
            $results = array_merge($results, $this->search($subarray, $key, $value));
    }

    return $results;
} 

小心
这个搜索功能是区分大小写的,它需要像匹配这样的修改 将 montreal 中的大写 M 更改为小写的键或值的百分比将为空

【讨论】:

  • 好的,太棒了。那么我究竟该如何实现呢?我收到此错误 - Parse error: syntax error, unexpected '=>' (T_DOUBLE_ARROW) in /home/matt/public_html/school/standings.php 在第 10 行。抱歉,如果它非常明显如何实现 - 我才开始学习 PHP ,嗯,今天。
  • 我似乎收到了这段代码的错误 - $search_result = $objXML->search($arrOutput, 'NAME', 'Montreal') 错误是 - 致命错误:调用未定义/home/matt/public_html/school/standings.php 第 17 行中的方法 xml2Array::search()
【解决方案2】:

这是我发送给您的实际代码。从您正在使用的同一链接中提取数据

http://sjsharktank.com/standings.php

实际上,我在自己的学校项目中使用了完全相同的 XML 文件。我使用了 DOM 文档。 foreach 循环将获取 team-standing 的每个属性的值并存储这些值。该代码将清除表排名的内容,然后重新插入数据。我猜你可以做一个更新语句,但这假设你从未在表中输入过任何数据。

 try {   
      $db = new PDO('sqlite:../../SharksDB/SharksDB');  
      $db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);  
    } catch (Exception $e) {  
       echo "Error: Could not connect to database.  Please try again later.";
       exit;
    }   
            $query = "DELETE FROM standings";
            $result = $db->query($query);

            $xmlDoc = new DOMDocument();
            $xmlDoc->load('http://www.tsn.ca/datafiles/XML/NHL/standings.xml');
            $searchNode = $xmlDoc->getElementsByTagName( "team-standing" ); 
            foreach ($searchNode as $searchNode) {
                $teamID = $searchNode->getAttribute('id');
                $name = $searchNode->getAttribute('name');
                $wins = $searchNode->getAttribute('wins');
                $losses = $searchNode->getAttribute('losses');
                $ot = $searchNode->getAttribute('overtime');
                $points = $searchNode->getAttribute('points');
                $goalsFor = $searchNode->getAttribute('goalsFor');
                $goalsAgainst = $searchNode->getAttribute('goalsAgainst');
                $confID = $searchNode->getAttribute('conf-id');
                $divID = $searchNode->getAttribute('division-id');

                $query = "INSERT INTO standings ('teamid','confid','divid','name','wins','losses','otl','pts','gf','ga')
                          VALUES ('$teamID','$confID','$divID','$name','$wins','$losses','$ot','$points','$goalsFor','$goalsAgainst')";
                $result= $db->query($query);
            }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-09
    • 2012-07-24
    相关资源
    最近更新 更多