Zulakis
Zulakis

Reputation: 8394

PHP DOMDocument value of element without child-elements

I got a DOMDocument which looks like this:

<font size="6" face="Arial">
CONTENT
    <font size="5" face="Arial">...</font>
    <br>
    <table cellspacing="1" cellpadding="1" border="3" bgcolor="#E7E7E7" rules="all">...</table>
    <table cellspacing="1" cellpadding="1">...</table>
    <font size="3" face="Arial" color="#000000">...</font>
</font>

Now I want to get just CONTENT and not all the other child-elements.

How can I do that?

Upvotes: 3

Views: 1913

Answers (2)

Zulakis
Zulakis

Reputation: 8394

Shorter:

$output = $xml->getElementsByTagName("font")->item(1)firstChild->textContent;

nickb's solution works too and is even better if the CONTENT comes after one of the sub-childs. But since it doesn't do that in my case, this one is shorter.

Upvotes: 2

nickb
nickb

Reputation: 59709

What you can do is grab the first DOMText node that's a child of the first <font> tag.

// Get the first <font> tag
$font = $doc->getElementsByTagName( 'font')->item(0);

// Find the first DOMText element
$first_text = null;
foreach( $font->childNodes as $child) {
    if( $child->nodeType === XML_TEXT_NODE) {
        $first_text = $child; 
        break;
    }
}

if( $first_text != null) {
    echo 'OUTPUT: ' . $first_text->textContent;
}

You can see from the demo that this prints:

OUTPUT: CONTENT

Upvotes: 3

Related Questions