【问题标题】:Unable to access value of attribute with dash in PHP using simple HTML DOM无法使用简单的 HTML DOM 在 PHP 中使用破折号访问属性值
【发布时间】:2015-05-05 04:06:09
【问题描述】:

我正在尝试使用 PHP Simple HTML DOM 获取一些 html 值并将它们存储在 PHP 数组中。

在 HTML 页面中,我要解析/获取以下内容:

<li id="1" data-name="Jason" class="result-names">
<li id="2" data-name="John" class="result-names">
<li id="3" data-name="Elco" class="result-names">
<li id="5" data-name="Dana" class="result-names">

我能够捕获“id”值和“class”值,但此时我似乎无法获取“data-name”的值。我用来实现这一目标的代码:

<?php
require_once('simple_html_dom.php');
$dom = file_get_html('http://localhost/names.html');
foreach($dom->find('li[class=result-names]') as $results) {
    $item['id']     = $results->id;
    $item['name'] = $results->data-name;          //this does not work 
    $item['class'] = $results->class;
    $articles[] = $item;
}

echo "<pre>";
print_r($articles);
echo "</pre>";

【问题讨论】:

  • 仅供参考,为什么使用 $item['class'] = $results->class;当你知道 class 是 "result-names" 时,直接使用它 $item['class'] = "result-names";

标签: php html web-scraping simple-html-dom


【解决方案1】:

用途:

$item['name'] = $results->getAttribute("data-name");

- 是减法运算符,它不能用作标识符的一部分。你写的内容被解析为:

$item['name'] = ($results->data) - name;

【讨论】:

    【解决方案2】:

    试试看:

    $item['name'] = $results->attr['data-name'];
    

    【讨论】:

      猜你喜欢
      • 2012-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-12
      • 1970-01-01
      • 2011-02-01
      • 2015-12-08
      相关资源
      最近更新 更多