duanao2688 2014-05-08 12:42
浏览 26
已采纳

如何在类中获取文本的json数组? [重复]

This question already has an answer here:

The html snippet in a url (www.foo.com/index.html):

...
<th class="name" align="left" scope="col">
<a class="foo" href="foo.html">foo</a>
</th>
...
<th class="name" align="left" scope="col">
<a class="bar" href="bar.html">bar</a>
</th>
...
<th class="name" align="left" scope="col">
<a class="ba" href="baz.html">baz</a>
</th>
......

I would like to get, through php all the text inside the class .name and convert it to JSON

So that it ends up like:

{"names":["foo","bar","baz"]}

This is what I have tried:

function linkExtractor($html){
    $nameArr = array();
    $doc = new DOMDocument();
    $doc->loadHTML($html);
    $names = //how do i get the elements?
    foreach($names as $name) {
        array_push($nameArr, $name);
    }
    return $imageArr;
}

echo json_encode(array("names" => linkExtractor($html)));
</div>
  • 写回答

2条回答 默认 最新

  • douwu5009 2014-05-08 12:46
    关注

    try this ...

    $html = "http://www.foo.com/index.html"; //is this right?
    function linkExtractor($html, $classname){
        $nameArr = array();
        $doc = new DOMDocument();
        $doc->loadHTML($html);
    
        $names = $doc->xpath("//*[@class='" . $classname . "']");
    
        foreach($names as $name) {
            array_push($nameArr, $name);
        }
        return $imageArr;
    }
    
    echo json_encode(array("names" => linkExtractor($html,".name")));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集
  • ¥15 在启动roslaunch时出现如下问题