【问题标题】:How to get a json array of the text within a class? [duplicate]如何获取类中文本的json数组? [复制]
【发布时间】:2014-06-25 20:43:51
【问题描述】:

url 中的 html sn-p (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>
......

我想通过 php 获取 .name 类中的所有文本并将其转换为 JSON

所以结果是这样的:

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

这是我尝试过的:

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

【问题讨论】:

  • 你为什么不试试 jquery 呢?
  • @Dwza 不会工作,因为 html 没有被执行...
  • 您通常使用 xpath 执行此操作。请在提问前使用搜索。
  • @hakre 怎么会是重复的?
  • @Maximilian:正是为此://how do i get the elements? 在您的问题中。

标签: php json


【解决方案1】:

试试这个...

$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")));

【讨论】:

  • 在你尝试这个之前,请放心,它不会起作用。
  • 我收到错误Missing argument 2 for linkExtractor(),
  • 使用编辑版本的答案...
  • @Maximilian:该错误只会阻止您获得下一个致命错误。请参阅链接副本,了解如何实际运行该 xpath 查询。
  • 为什么这不起作用?好像应该?
【解决方案2】:

这样就结束了:

$names = function($html) {
    $doc  = new DOMDocument();
    $last = libxml_use_internal_errors(TRUE);
    $doc->loadHTML($html);
    libxml_use_internal_errors($last);
    $xp     = new DOMXPath($doc);
    $result = array();
    foreach ($xp->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' name ')]") as $node)
        $result[trim($node->textContent)] = 1;
    return array_keys($result);
};

echo json_encode(array("names" => $names($html)));

输出:

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

所需的 PHP 版本:5.3+

【讨论】:

  • 这不返回任何内容。
  • 赞这个{"names":[]}
  • 如果您看到该输出,这意味着它通常可以工作,但是 HTML 与您在问题中所写的不同。如您所见,它完美运行:3v4l.org/3TUPb - 因此,如果您提供的 HTML 不包含此类内容(例如,由于明显无效,因此 DOM 拒绝加载),请先修复 HTML。您可能只是遇到了一些 HTML 问题,与遍历节点完全无关。
猜你喜欢
  • 2015-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-11
  • 2019-05-23
  • 1970-01-01
  • 2014-08-03
相关资源
最近更新 更多