Search code examples
phpfile-get-contentsexplodeexternal-url

php only retrieving one string from external div from url


I am trying to link my page to another website in which I can use there div tags in order to keep my site up to date.

I've got some code after some research and it's echoing out just 1 string whereas there are multiple div classes on the page and I would like to echo them all. I am just wondering if this is possible or not?

Here is the current code:

<?php
$url = 'http://www.domain.com';
$content = file_get_contents($url);
$activity = explode( '<div class="class">' , $content );
$activity_second = explode("</div>" , $activity );

echo $activity_second[0];
?>

I can echo $activity_second[0] which will display the first line and $activity_second[1] which will display the second line.

However, I am looking to expand this over to allow all of the div classes on the same page to be put into an array which can then be echo'd out into different parts of a table.

Thank you for your help in advance.


Solution

  • Let me see if I get it straight, you have something like this:

    <div id="another-class"><div class="class">some text 1</div></div>
    <div class="class">some text 2</div>
    <div class="class">some text 3</div>
    <div class="class">some text 4</div>
    <div class="class">some text 5</div>
    <div class="class">some text 6</div>
    

    And you need the text contained the div elements. If this is correct, replace:

    $activity = explode( '<div class="class">' , $content );
    $activity_second = explode("</div>" , $activity );
    

    with this:

    preg_match_all('#<div class="class">(.+?)</div>#', $content, $matches);
    

    In this example, after the function call $matches will have the following:

    Array
    (
        [0] => Array
            (
                [0] => <div class="class">some text 1</div>
                [1] => <div class="class">some text 2</div>
                [2] => <div class="class">some text 3</div>
                [3] => <div class="class">some text 4</div>
                [4] => <div class="class">some text 5</div>
                [5] => <div class="class">some text 6</div>
            )
    
        [1] => Array
            (
                [0] => some text 1
                [1] => some text 2
                [2] => some text 3
                [3] => some text 4
                [4] => some text 5
                [5] => some text 6
            )
    
    )
    

    The data you need is in $matches[1].