3

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>

    <div 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>

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@jennifer: Sorry, my mistake. I corrected the answer. Also, it does not make any difference how many instances you have. The interface to access the query results is the same no matter what.
thank you! i think its working but the page is blank when i reload but no text

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.