我在试着从一个网站上删除数据。我坚持收视率。他们有这样的东西:
<div class="rating-static rating-10 margin-top-none margin-bottom-sm"></div>
<div class="rating-static rating-13 margin-top-none margin-bottom-sm"></div>
<div class="rating-static rating-46 margin-top-none margin-bottom-sm"></div>在我的例子中,rating-10实际上是一颗星,rating-13是两颗星,在我的脚本中,rating-46将是五星。
评级范围可以从0到50。
我的计划是创建switch,如果我的等级范围为1-10,我就会知道这是一颗星,11-20,两颗星等等。
任何想法,任何帮助都将不胜感激。
发布于 2015-09-08 09:27:15
尝尝这个
<?php
$data = '<div class="rating-static rating-10 margin-top-none margin-bottom-sm"></div>';
$dom = new DOMDocument;
$dom->loadHTML($data);
$xpath = new DomXpath($dom);
$div = $dom->getElementsByTagName('div')[0];
$div_style = $div->getAttribute('class');
$final_data = explode(" ",$div_style);
echo $final_data[1];
?>这将为您提供预期的输出。
发布于 2015-09-08 09:38:35
我有一个类似的项目,如果您想解析整个HTML站点,这应该是实现它的方法。
$dom = new DOMDocument();
$dom->loadHTML($html); // The HTML Source of the website
foreach ($dom->getElementsByTagName('div') as $node){
if($node->getAttribute("class") == "rating-static"){
$array = explode(" ", $node->getAttribute("class"));
$ratingArray = explode("-", $array[1]); // $array[1] is rating-10
//$ratingArray[1] would be 10
// do whatever you like with the information
}
}可能您必须将if部件更改为strpos检查,我还没有测试这个脚本,但我认为getAttribute("class")返回所有类。这将是if语句
if(strpos($node->getAttribute("class"), "rating-static") !== false)发布于 2015-09-08 11:19:25
FYI尝试使用Querypath来满足未来的解析需求。它只是PHP DOM解析器的包装器,工作非常好。
https://stackoverflow.com/questions/32453749
复制相似问题