0

I read this article - Get DIV content from external Website . I get source of website with file_get_contents() function and I have to extract from it content of two divs with same class name.

I have very similar problem, but with divs with same class name. E.g. I have code like that:

<div class="baaa">
Some conete
</div>
<div class="baaa">
Second Content
</div>

I want to get both content of both these divs. Solution accepted in article I linked support only one. My expected result is array like this:

$divs[0] = "Some conete"
$divs[1] = "Second Content"

Please give me advice what to do. I read about DOMDocument class, but have no idea how to use it.

6
  • Use each function in JQuery to get value of all div tags. `$(".baaa").each(function(){}); Commented Jan 8, 2015 at 18:14
  • try to use preg_match_all() Commented Jan 8, 2015 at 18:14
  • @bcesars I need to use PHP Commented Jan 8, 2015 at 18:15
  • @violator667 Can you explain? Commented Jan 8, 2015 at 18:16
  • 1
    See here: stackoverflow.com/questions/15761115/… Commented Jan 8, 2015 at 18:17

4 Answers 4

1

i have used the simple html dom parser and your content can be extracted as

$html = file_get_html('your html file link');
$k=1;
foreach($html->find('div.baaa') as $e){
        $divs[$k]=$e;
        $k++;
    }
echo $divs[1]."<br>";
echo $divs[2];
Sign up to request clarification or add additional context in comments.

Comments

0

You could use XPath. XPath is a query language for XML. There are PHP functions that support Xpath. For you the example could be:

File test.html:

<html>
<body>
<div class="baaa">
Some conete
</div>
<div class="baaa">
Second Content
</div>
</body>
</html>

The php code that extracts contents of divs with the class "baaa"

$xml = simplexml_load_file('test.html');
$data = $xml->xpath('//div[@class="baaa"]/text()');
foreach($data as $row) {
    printf($row);
}

generates the following output:

Some conete
Second Content

Look for XPath tutorials if you need more complex searching or analyzing.

Comments

-1

Try it with your data:

$file_contents = file_get_contents('http://address.com');
preg_match_all('/<div class=\"baaa\">(.*?)<\/div>/s',$file_contents,$matches);
print_r($matches);

BTW: Polska rządzi :)

1 Comment

To prawda - Polska rządzi :D
-1
<script type="text/javascript">
$(document).ready(function(){
    $('.baaa').each(function(){
        alert($(this).text());
    });
});
</script>

<div class="baaa">
Some conete
</div>
<div class="baaa">
Second Content
</div>

1 Comment

He said he needs to use PHP

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.