Search code examples
phpsimple-html-dom

Simple Dom HTML tags without attributes


Hello I am trying to pull back roster information from ESPN.com. Each team's roster is saved into a table. I am trying to figure a way to save each tag into a variable as appropriate however each tag does not have an ID such as "jersey_number"/"player_name" so search through this has given me some problems. Here is what I have so far - If you could give me a pointer or 2 that would be much appreciated.

    <?php
    require_once("../tools/simple_html_dom.php");
    require_once("../tools/Utilities.php");
    $url = "http://espn.go.com/nfl/team/roster/_/name/den/denver-broncos";

    $espnHTML = file_get_html("http://espn.go.com/nfl/team/roster/_/name/den/denver-broncos");



    foreach($espnHTML->find("table.tablehead",0)->find('tr[class^=odd]') as $rosterRow)
    {
        foreach($rosterRow->find("td") as $playerInfo)
        {
            echo $playerInfo->plaintext."<br>";   
        }

    }
   ?>

How can I assign these td tags into appropriate variables without "ids"? Attached is a sample screenshot that may help you understand what I am talking about. enter image description here


Solution

  • If the columns are in the same order for every player, using your $rosterrow->find("td") should return an indexed array that you can access using $playerrow[0..n]. Then, by analyzing what corresponds to what you can make a function like this:

    $players = array();
    foreach($espnHTML->find("table.tablehead",0)->find('tr[class^=odd]') as $rosterRow)
    {
        $playerRow = $rosterRow->find("td");
        $name = $playerRow[0];
        $jersey = $playerRow[1];
        // more can be added, of course.
    
        $players[$name] = array();
        $players[$name]["jersey"] = $jersey;
        // and others
    }
    

    For table

    John Appleseed | 12
    ---------------|----
    Richard Brooks | 34
    

    this will result in an array like

    { "John Appleseed" => { "jersey" => 12 }, "Richard Brooks" => { "jersey" => 34}}
    

    Please let me know if this helped.