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条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!