0

I want to get the value of each field like "Delhi" , "Kolkatta".

How can i do this using php DOM Script ?

here is the source of the page to parsed.

<tbody><tr>
<td>Delhi</td>
<td>66.91</td>
</tr>
<tr>
<td>Kolkata</td>
<td>69.52</td>
</tr>
<tr>
<td>Mumbai</td>
<td>78.44</td>   
</tr>
<tr>
<td>Chennai</td>
<td>69.93</td>
</tr></tbody> 
0

3 Answers 3

1

Here we are using DOMDocument to achieve desired output.

Try this code snippet here

$domDocument = new DOMDocument();
$domDocument->loadHTML($string);

$domXPath = new DOMXPath($domDocument);
$results = $domXPath->query("//tbody/tr/td");
$data=array();
for($x=0;$x<$results->length;$x+=2)
{
    $instance=$results->item($x);
    if($instance instanceof DOMElement)
    {
        $data[]=$results->item($x)->textContent;
    }
}
print_r($data);
Sign up to request clarification or add additional context in comments.

Comments

0

Alternatively you can use simplexml function, please someone correct me if it is wrong way or bad idea

$xml='<tbody><tr>
<td>Delhi</td>
<td>66.91</td>
</tr>
<tr>
<td>Kolkata</td>
<td>69.52</td>
</tr>
<tr>
<td>Mumbai</td>
<td>78.44</td>   
</tr>
<tr>
<td>Chennai</td>
<td>69.93</td>
</tr></tbody> ';
echo "<pre>";
$arr=simplexml_load_string($xml);
$arr_new=array();
$arr1=json_decode(json_encode((array)$arr), TRUE);
foreach($arr1 as $val){
    foreach($val as $k=>$v){
        $arr_new[$val[$k]['td'][0]]=$val[$k]['td'][1];
    }
}

Output

Array
(
    [Delhi] => 66.91
    [Kolkata] => 69.52
    [Mumbai] => 78.44
    [Chennai] => 69.93
)

Comments

0

See question here: How do you parse and process HTML/XML in PHP?

How to use the DOM extension has been covered extensively on StackOverflow, so if you choose to use it, you can be sure most of the issues you run into can be solved by searching/browsing Stack Overflow

Here an example:

$html = <<<HTML
<tbody><tr>
<td>Delhi</td>
<td>66.91</td>
</tr>
<tr>
<td>Kolkata</td>
<td>69.52</td>
</tr>
<tr>
<td>Mumbai</td>
<td>78.44</td>
</tr>
<tr>
<td>Chennai</td>
<td>69.93</td>
</tr></tbody>
HTML;

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

$elements = $dom->getElementsByTagName('tr');
$data = [];
foreach($elements as $node) {
    $childElements = $node->getElementsByTagName('td');
    $data[$childElements->item(0)->nodeValue] = $childElements->item(1)->nodeValue;
}

Comments

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.