php获取sitemap里面指定数量的网址URL并且保存到本地的TXT文本里面

u0110baidu 2015-08-23 05:45:27
例如获取这个页面的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..还希望大家指导一下,谢谢,尽量说得详细一点,非常谢谢.*_*
...全文
452 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
xuzuning 2015-08-23
  • 打赏
  • 举报
回复
$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));

21,873

社区成员

发帖
与我相关
我的任务
社区描述
从PHP安装配置,PHP入门,PHP基础到PHP应用
社区管理员
  • 基础编程社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧