开发者

How to convert list data to table in php

I'm creating a hockey website using wordpress. I have a custom menu of Hockey players and im using wp_nav_menu to get html like this:

<ul id="example-menu">
<li><a href="/example/">[3] [DeBlois] [USA] [20 yr] [5’11] [185 lbs]</a></li>
<li><a href="/example/">[35] [Baldino] [USA] [20 yr] [5’11] [185 lbs]开发者_如何学JAVA</a></li>
<li><a href="/example/">[2] [Esch] [USA] [20 yr] [5’11] [185 lbs]</a></li>
</ul>

before echoing this onto the page, I want to break it into an array and put it back together in a table so each column is lined up nicely. I also need to replace the [USA] part with a graphic, which will be easy to do once I get the list into the array.

What's the best way to parse through this type of html? Is there a different function I can use in WP?


<?php

$html = '<ul id="example-menu">
<li><a href="/example/">[3] [DeBlois] [USA] [20 yr] [5’11] [185 lbs]</a></li>
<li><a href="/example/">[35] [Baldino] [USA] [20 yr] [5’11] [185 lbs]</a></li>
<li><a href="/example/">[2] [Esch] [USA] [20 yr] [5’11] [185 lbs]</a></li>
</ul>';


$doc = new DOMDocument();
@$doc->loadHTMl( $html);
$link_array =  $doc->getElementsByTagName('a');


$result = array();

foreach($link_array as $element )
{
    $value  = $element->nodeValue;
    $value = str_replace('[','',$value);
    $value = str_replace(']','',$value);

    $row =  explode(" ",$value);

    $result[] = $row;
    unset($row);
}

echo "<pre>";
print_r($result);
echo "</pre>";
?>

OUTPUT

    Array
(
    [0] => Array
        (
            [0] => 3
            [1] => DeBlois
            [2] => USA
            [3] => 20
            [4] => yr
            [5] => 5’11
            [6] => 185
            [7] => lbs
        )

    [1] => Array
        (
            [0] => 35
            [1] => Baldino
            [2] => USA
            [3] => 20
            [4] => yr
            [5] => 5’11
            [6] => 185
            [7] => lbs
        )

    [2] => Array
        (
            [0] => 2
            [1] => Esch
            [2] => USA
            [3] => 20
            [4] => yr
            [5] => 5’11
            [6] => 185
            [7] => lbs
        )

)


If you are scraping from another website as dmcnelis suggested, you could look into using a combination of PHP's Dom getElementById and then exploding on the ']' character while stripping '['.


You could explode with

'<li>'

and strip_tags() to get the rows (ignoring the first one), and loop through them and explode with

'] [' 

to get the cols.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜