【问题标题】:SimpleXML: trouble with parent with attributesSimpleXML:带有属性的父级问题
【发布时间】:2014-12-03 18:45:40
【问题描述】:

需要帮助更新我之前所做的一些 simplexml 代码。我正在解析的 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 对我来说一直是个谜 :)

【问题讨论】:

    标签: php xml xpath xml-parsing simplexml


    【解决方案1】:

    您之前遍历了位于根元素中的所有 &lt;pinfo&gt; 元素:

    foreach ($pinfo as $resource) 
    

    现在所有&lt;pinfo&gt; 元素都已从根元素移动到&lt;category&gt; 元素中。您现在需要先查询这些元素:

    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
    }
    

    【讨论】:

    【解决方案2】:

    当您加载 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
        }
    }
    

    【讨论】:

    • 感谢您的回答!我知道这很简单,但我从来不知道每个元素都以数组的形式存在 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-23
    • 2011-03-29
    • 2021-03-26
    • 2011-01-11
    • 1970-01-01
    • 2021-11-05
    • 1970-01-01
    相关资源
    最近更新 更多