php - Simple HTML DOM Parser - Get all plaintex rather than text of certain element

630

I tried all the solutions posted on this question. Although it is similar to my question, it's solutions aren't working for me.

I am trying to get the plain text that is outside of<b> and it should be inside the<div id="maindiv>.

<div id=maindiv>
     <b>I don't want this text</b>
     I want this text
</div>

$part is the object that contains<div id="maindiv">. Now I tried this:

$part->find('!b')->innertext;

The code above is not working. When I tried this

$part->plaintext;

it returned all of the plain text like this

I don't want this text I want this text

I read the official documentation, but I didn't find anything to resolve this:

815

Answer

Solution:

Query:

$selector->query('//div[@id="maindiv"]/text()[2]')

Explanation:

//               - selects nodes regardless of their position in tree

div              - selects elements which node name is 'div'

[@id="maindiv"]  - selects only those divs having the attribute id="maindiv"

/                - sets focus to the div element

text()           - selects only text elements

[2]              - selects the second text element (the first is whitespace)

                   Note! The actual position of the text element may depend on
                   your preserveWhitespace setting.

                   Manual: http://www.php.net/manual/de/class.domdocument.php#domdocument.props.preservewhitespace

Example:

$html = <<<EOF
<div id="maindiv">
     <b>I dont want this text</b>
     I want this text
</div>
EOF;

$doc = new DOMDocument();
$doc->loadHTML($html);

$selector = new DOMXpath($doc);   

$node = $selector->query('//div[@id="maindiv"]/text()[2]')->item(0);
echo trim($node->nodeValue); // I want this text
178

Answer

Solution:

remove the<b> first:

$part->find('b', 0)->outertext = '';
echo $part->innertext; // I want this text

People are also looking for solutions to the problem: php - New Session login details

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.