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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里