开发者

Parse span class text with DOM PHP

I've been having an issue trying to parse text in a span class with DOM. Here is my code example.

$remote = "http://website.com/";
$doc = new DOMDocument();
@$doc->loadHTMLFile($remote);
$xpath = new DOMXpath($doc);
$node = $xpath->query('//span[@class="user"]');
echo $node;

and this returns the following error -> "Catchable fatal error: Object of class DOMNodeList could not be converted to string". I am so lost I NEED HELP!!!

What I am trying to do is parse the user name between this span tag.

<span class="user">bballgod093</span>

Here is the full source from the remote website.

<div id="randomwinner">
    <div id="rndmLeftCont">
        <h2 id="rndmTitle">Hourly Random <span>Winner</span></h2>
    </div>
    <div id="rndmRightCont">
        <div id="rndmClaimImg">
            <table cellspacing="0" cellpadding="0" width="200">
                <tbody>
                    <tr>
                        <td align="right" valign="middle">
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    <div id="rndmCaimTop">

    <span class="user">bballgod093</span>You've won 1000 SB</div>

    <d开发者_如何学Civ id="rndmCaimBottom">
        <a id="rndmCaimBtn" class="btn1 btn2" href="/?cmd=cp-claim-random" rel="nofollow">Claim Bucks</a>
    </div>

    </div>
    <div class="clear"></div>
</div>


This call

$node = $xpath->query('//span[@class="user"]');

does not return a string, but a DOMNodeList.

You can use this list somewhat like array (using $node->length for the number of elements and $node->item(0) to get the first element) to get DOMNode objects. Each of these objects has a nodeValue property which is a string.

So you would do something like

$node = $xpath->query('//span[@class="user"]');
if($node->length != 1) {
    // error?
}

echo $node->item(0)->nodeValue;

Of course, changing the variable name for $node to something more appropriate would be nice.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜