-5

I want to display HTML content which contain multiple divs with same class names and different id names. I would like to place the content into array form like below:

HTML Content:

<div id='divcont'>
    <div class='abc'>
        <P class='first'>test1</p>
    </div>
    <div class='abc'>
        <P class='first_sec'>test2</p>
    </div>
</div>

Result:

Array
(
    [0] => <P class='first'>test1</p>
    [1] => <P class='first_sec'>test2</p>
)
  • 1
    What have you tried so far? Please show your code. Also, is this the only HTML you'd need to analyze? If not, what are the rules for the input you need to analyze? – Surreal Dreams Jan 21 '15 at 16:06
  • **Don't use regular expressions to parse HTML. Use a proper HTML parsing module.** You cannot reliably parse HTML with regular expressions, and you will face sorrow and frustration down the road. As soon as the HTML changes from your expectations, your code will be broken. See http://htmlparsing.com/php or [this SO thread](http://stackoverflow.com/questions/3577641/how-do-you-parse-and-process-html-xml-in-php) for examples of how to properly parse HTML with PHP modules that have already been written, tested and debugged. – Andy Lester Jan 21 '15 at 16:08
  • yes, can you check with the above question, – user2431105 Jan 27 '15 at 09:53

1 Answers1

3

You can achieve this simple task using the right tool for the job.

$doc = DOMDocument::loadHTML("
<div id='divcont'>
    <div class='abc'>
        test1
    </div>
    <div class='abc'>
        test2
    </div>
</div>
");

$xpath = new DOMXPath($doc);
$nodes = $xpath->query('//div[@class="abc"]');

foreach ($nodes as $node) {
   $data[] = trim($node->nodeValue);
}

print_r($data);

Output

Array
(
    [0] => test1
    [1] => test2
)
hwnd
  • 69,796
  • 4
  • 95
  • 132