需要帮助更新我以前做的一些简单的xml代码。我正在解析的XML文件以一种新的方式格式化,但我不知道如何导航
旧XML格式示例:
<?xml version="1.0" encoding="UTF-8"?>
<pf version="1.0">
<pinfo>
<pid><![CDATA[test1 pid]]></pid>
<picture><![CDATA[http://test1.image]]></picture>
</pinfo>
<pinfo>
<pid><![CDATA[test2 pid]]></pid>
<picture><![CDATA[http://test2.image]]></picture>
</pinfo>
</pf>
然后是新的XML格式(注意添加了"类别名称"):
<?xml version="1.0" encoding="UTF-8"?>
<pf version="1.2">
<category name="Cname1">
<pinfo>
<pid><![CDATA[test1 pid]]></pid>
<picture><![CDATA[http://test1.image]]></picture>
</pinfo>
</category>
<category name="Cname2">
<pinfo>
<pid><![CDATA[test2 pid]]></pid>
<picture><![CDATA[http://test2.image]]></picture>
</pinfo>
</category>
</pf>
在XML中添加了"类别名称"之后,旧的解析代码就不起作用了:
$pinfo = new SimpleXMLElement($_SERVER['DOCUMENT_ROOT'].'/xml/file.xml', null, true);
foreach($pinfo as $resource)
{
$Profile_id = $resource->pid;
$Image_url = $resource->picture;
// and then some echo´ing of the collected data inside the loop
}
我需要添加什么或做完全不同的事情?我尝试过xpath、children和按属性排序,但没有成功——SimpleXML对我来说一直是个谜:)
您之前迭代了位于根元素中的所有<pinfo>
元素:
foreach ($pinfo as $resource)
现在,所有<pinfo>
元素都已从根元素移动到<category>
元素中。您现在需要首先查询这些元素:
foreach ($pinfo->xpath('/*/category/pinfo') as $resource)
现在命名错误的变量$pinfo
有点挡住了去路,所以它最好做更多的更改:
$xml = new SimpleXMLElement($_SERVER['DOCUMENT_ROOT'].'/xml/file.xml', null, true);
$pinfos = $xml->xpath('/*/category/pinfo');
foreach ($pinfos as $pinfo) {
$Profile_id = $pinfo->pid;
$Image_url = $pinfo->picture;
// ... and then some echo´ing of the collected data inside the loop
}
加载XML文件时,类别元素作为它们自己的数组存在。您用来解析的XML包含在中。您所需要做的就是用另一个foreach
包装当前代码。除此之外,没有什么可改变的。
foreach($pinfo as $category)
{
foreach($category as $resource)
{
$Profile_id = $resource->pid;
$Image_url = $resource->picture;
// and then some echo´ing of the collected data inside the loop
}
}