【发布时间】:2016-02-28 11:04:36
【问题描述】:
我有以下 XML 架构:
<url>
<loc>
https://www.domain.com/artcile-title-x
</loc>
<mobile:mobile/>
<image:image>
<image:loc>
https://www.domain.com/images/file_name.jpg
</image:loc>
<image:title>file_name.jpg</image:title>
</image:image>
<lastmod>2015-11-29T06:17:25+00:00</lastmod>
<changefreq>monthly</changefreq>
</url>
使用 simplexml_load_file 函数,我可以正确提取“loc”。问题在于“图像”。我尝试了很多测试,但没有。也许 simplexml_load_file 不是正确的?
例如:
//XML url location
$xmlurl = "https://www.domain.com/sitemap.xml";
//get the content in the $xmlcode var
$xmlcode = simplexml_load_file($xmlurl);
//for each "section" extracted obtain LOC and IMAGE
foreach($xmlcode->url as $single_section)
{
//obtain the information URL->LOC
$loc_extracted = $single_section->loc;
echo "URL Extracted: " . $loc_extracted . "<br>";
//obtain the information URL->IMAGE
$image_extracted = $single_section->image->loc;
echo "IMG Extracted: " . $image_extracted[0] . "<br>";
}
我已经尝试了很多测试,例如:
$image_extracted = $single_section->image->image->loc;
or
$image_extracted = $single_section->image->image->image->loc;
or
$image_extracted = $single_section->image; //and use it as an array
or
$image_extracted = $single_section->image['image']->loc;
or
$image_extracted = $single_section->image['image']->image->loc;
观察 XML 文件及其构建方式非常重要。 从同一个“url”部分我必须提取“loc”和“images:images/images:loc”细节。
我尝试了这个可能的解决方案:Parse XML with Namespace using SimpleXML
但它不适合提取简单参数(loc)和带节点参数(images/loc)的需要。
【问题讨论】:
标签: php xml xml-parsing parent-child