ghostrider
ghostrider

Reputation: 5259

getting value using xpath and dom in php

this the part of the html i want to parse:

<center>
<table border="0" cellpadding="0" cellspacing="0"  >
<td>
Some text
<br>
<font color=brown>label0</font>Value0
<br>
<font color=brown>Label1</font>Value1.<br>
Some text
<br>

<font color=brown>Label2</font>Value2<br>
</td>
</table>

</center>

I want to get Value0 and Value1.

If i use this:

$index=$element->nodeValue;

where element is the query to the .../font I get the Label0,1,2. But I want the Value. How to do it? I can also give more code if it is necessary.

Upvotes: 3

Views: 319

Answers (4)

Jelmer
Jelmer

Reputation: 2693

$dom = new DOMDocument();
$xpath = new DOMXPath($dom);    
$xpath->loadHTML('link/to/html');
$fonts = $xpath->query('font');
foreach ($fonts as $font){
    echo $font->nextSibling->nodeValue;
}

The script above will echo all the values of that's what is inside the <font>.

But please, why aren't you using CSS?

Upvotes: -1

Nipun Jain
Nipun Jain

Reputation: 601

<center>
<table border="0" cellpadding="0" cellspacing="0"  >
<td>
Some text
<br>
<font color=brown>label0</font><span>Value0</span>
<br>
<font color=brown>Label1</font><span>Value1.</span><br>
Some text
<br>

<font color=brown>Label2</font>Value2<br>
</td>
</table>
</center>

try putting span just as above and instead of quering font query for span... hope it will help..

Upvotes: 1

web-nomad
web-nomad

Reputation: 6003

Try this:

$str = '<center>
<table border="0" cellpadding="0" cellspacing="0"  >
<td>
Some text
<br>
<font color=brown>label0</font>Value0
<br>
<font color=brown>Label1</font>Value1.<br>
Some text
<br>

<font color=brown>Label2</font>Value2<br>
</td>
</table>
</center>';

$dom = new DOMDocument();
$dom->loadHTML($str);
$dom->preserveWhiteSpace = false;
$dom->validateOnParse = true;

$xpath = new DOMXPath($dom);
$nodes = $xpath->query("//font");
foreach ($nodes as $node) {
    echo trim( $node->nextSibling->nodeValue ) . "\n";
}

Hope this helps.

Upvotes: 0

yiding
yiding

Reputation: 3590

Try perhaps:

$index=$element->nextSibling->nodeValue;

To get the value of the node after the font node.

Upvotes: 2

Related Questions