【问题标题】:Php parse content from url by class name [closed]Php按类名解析来自url的内容[关闭]
【发布时间】:2020-06-24 18:45:53
【问题描述】:

我无法从另一个链接中找到正确的解析解决方案。我想解析部分网站的内容。

我需要得到字符串“Director”。

<div>
    <div class="jobtitle">Director</div>
</div>
 

这是显示链接中所有内容的代码

$url = 'somelink.com';
$result = file_get_contents($url);

echo($result);

【问题讨论】:

  • 你能说得更具体些吗?
  • 向我们展示您的 parse() 函数,并告诉我们什么不能按预期工作 - 实际结果与预期结果。并让我们详细了解您尝试调试代码的内容。请阅读How to Ask
  • 是否要检索具有特定类的元素的内容?你说的是这个吗?
  • @bestprogrammerintheworld 绝对是的
  • @bestprogrammerintheworld 感谢图书馆,我的任务的最佳解决方案。

标签: php


【解决方案1】:

试试:

$url = 'somelink.com';
$result = file_get_contents($url);

$dom = new DOMDocument;
$dom->loadHTML($result);

$classname="jobtitle";
$finder = new DomXPath($dom);
$spaner = $finder->query("//*[contains(@class, '$classname')]");

或者,如果您不想使用 XPath 遍历,您可以简单地循环遍历所有 div 节点并获取等于“jobtitle”的class 属性。

这是代码:

$url = 'somelink.com';
$result = file_get_contents($url);

$dom = new DOMDocument;
$dom->loadHTML($result);

$nodes = $dom->getElementsByTagName ("div");

$wanted_node ;

foreach( $nodes $n) {
    if ($n->getAttribute('class') == "jobtitle"){
        $wanted_node = $n;
    }
}

//If wanted_node is not null(the node with class=jobtitle is found
if (isset ($wanted_node)){
    echo $wanted_node;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-31
    • 1970-01-01
    • 2012-05-14
    • 1970-01-01
    相关资源
    最近更新 更多