drnx3715 2013-11-18 20:17
浏览 29
已采纳

PHP从HTML剥离[关闭]

I'm trying to use PHP to return three simple variables from a web page. The web page is: http://areacode.org/519 My code is below:

<!doctype html>
<html>
<head>
<title>Untitled Document</title>
</head>
<?php
//variables
    $quickurl = idk;
    $country = idk;
    $State = idk;
    $city = idk;
//end of variables
    $test = file_get_contents("http://areacode.org/519");
    //$strip = strip_tags($test); Not sure if this is needed.
    echo ("<center>Info about Area code! Country: ".$country.". State: ".$state.". City: ".$city.". Quick reference URL: ".$quickurl."</center>");
?>
<body>
</body>
</html>

I am attempting to strip out the country, state, and major city and the quick url. I have looked around, but no help. I think I may just be a little confused. Any help?

  • 写回答

2条回答 默认 最新

  • dongzhi4498 2013-11-18 20:38
    关注

    All you need is DOM and XPath:

    $dom = new DOMDocument;
    @$dom->loadHTMLFile('http://areacode.org/519');
    $xpath = new DOMXPath($dom);
    $data = $xpath->query("//div[@class='info']//span[@class='value']");
    list($country, $state, $city, $url) = array_map(function ($node) {
            return trim($node->nodeValue, "\xc2\xa0"); // strip non-breaking spaces found on source
        }, iterator_to_array($data));
    var_dump($country, $state, $city, $url);
    

    This gave me the following:

    string(6) "Canada"
    string(7) "Ontario"
    string(6) "London"
    string(16) "areacode.org/519"
    

    That's all!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 matlab实现基于主成分变换的图像融合。
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊