例如获取这个页面的http://localhost/sitemap.xml里面的内容如下所示<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>http://localhost/</loc>
<lastmod>2015-08-22T11:04:37+00:00</lastmod>
<changefreq>always</changefreq>
<priority>1.0</priority>
</url>
<url>
<loc>http://localhost/?post=362</loc>
<lastmod>2015-08-22T10:14:51+00:00</lastmod>
<changefreq>weekly</changefreq>
<priority>0.8</priority>
</url>
<url>
<loc>http://localhost/?post=361</loc>
<lastmod>2015-08-22T08:01:12+00:00</lastmod>
<changefreq>weekly</changefreq>
<priority>0.8</priority>
</url>.............
我想要获取里面的<loc></loc>之间的URL(最好是可以设置获取URL的数量或者说顺序) ---   http://localhost/?post=361 并且保存到本地的TXT文本里面(一条URL一行),php代码该如何操作 ?PS:试了一些截取方法没有成功,刚刚学习php..还希望大家指导一下,谢谢,尽量说得详细一点,非常谢谢.*_*

解决方案 »

  1.   

    $s =<<< XML
    <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
    <loc>http://localhost/</loc>
    <lastmod>2015-08-22T11:04:37+00:00</lastmod>
    <changefreq>always</changefreq>
    <priority>1.0</priority>
    </url>
    <url>
    <loc>http://localhost/?post=362</loc>
    <lastmod>2015-08-22T10:14:51+00:00</lastmod>
    <changefreq>weekly</changefreq>
    <priority>0.8</priority>
    </url>
    <url>
    <loc>http://localhost/?post=361</loc>
    <lastmod>2015-08-22T08:01:12+00:00</lastmod>
    <changefreq>weekly</changefreq>
    <priority>0.8</priority>
    </url>
    </urlset>
    XML;$x = simplexml_load_string($s);
    print_r($x);
    SimpleXMLElement Object
    (
        [url] => Array
            (
                [0] => SimpleXMLElement Object
                    (
                        [loc] => http://localhost/
                        [lastmod] => 2015-08-22T11:04:37+00:00
                        [changefreq] => always
                        [priority] => 1.0
                    )            [1] => SimpleXMLElement Object
                    (
                        [loc] => http://localhost/?post=362
                        [lastmod] => 2015-08-22T10:14:51+00:00
                        [changefreq] => weekly
                        [priority] => 0.8
                    )            [2] => SimpleXMLElement Object
                    (
                        [loc] => http://localhost/?post=361
                        [lastmod] => 2015-08-22T08:01:12+00:00
                        [changefreq] => weekly
                        [priority] => 0.8
                    )        ))可知foreach($x->url as $v) $r[] = $v->loc;
    file_put_contents('文件.txt', join(PHP_EOL, $r));