无法获取数据标题,只是数据slug

时间:2018-02-14 14:37:37

标签: php simple-html-dom

HTML

<article class="movie-summary" data-slug="slug-goes-here" data-title="This is a Title">
...
...
</article>

PHP

$html = file_get_html( 'example.com' );
foreach( $html->find('article') as $data) {
    $property = 'data-title';
    echo $data->$property;
}

嘿所有,所以我希望能够从特定网站的所有文章中获取所有数据标题。当我使用data-slug时,当我使用数据标题时,我得到了数据,在this post

的帮助下我得不到任何结果

3 个答案:

答案 0 :(得分:0)

尝试将数据转换为数组

$html = file_get_html( 'example.com' );
foreach( $html->find('article') as $data) {
    $data = (array) $data;
    var_dump($data);
}

答案 1 :(得分:0)

这很简单,验证结果

<?php
include 'simple_html_dom.php';
$html = str_get_html('<article class="movie-summary" data-slug="slug-goes-here" data-title="This is a Title"></article>');

    foreach( $html->find('article') as $data) {
        $property = 'data-title';
        echo $data->$property;
    }

?>

https://sourceforge.net/projects/simplehtmldom/files/

获取文件'simple_html_dom.php'

输出:

enter image description here

答案 2 :(得分:0)

如果您查看您尝试解析的实际HTML代码(评论中提供的链接),您会发现它无效:

<article  class="movie-summary hero" data-slug="aiyaary-hindi"data-title="Aiyaary">
...
</article>

意思是,data-slugdata-title属性之间没有空格。所以为了解决这个问题,我建议添加必要的空间。像这样:

function placeNeccessarySpaces($contents) {
    return preg_replace('/"data-title/', '" data-title', $contents);
}

这类似于this answer。然后:

$contents = placeNeccessarySpaces(file_get_contents('http://example.com'));
$html = str_get_html($contents);
foreach( $html->find('article') as $data) {
    $property = 'data-title';
    echo $data->$property;
}