dongyi8383 2016-03-16 15:36
浏览 58
已采纳

php只从url中检索外部div中的一个字符串

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.

  • 写回答

4条回答 默认 最新

  • doupian9490 2016-03-16 16:01
    关注

    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].

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么