使用PHP使用SimpleXML解析XML并且存在命名空间问题

时间:2013-05-31 16:50:15

标签: php xml parsing namespaces simplexml

在SO和PHP.net上有很多关于使用PHP来处理XML的信息,但我在找到任何能够像设置XML一样使用命名空间的方法时遇到了问题。我根本没有使用XML的经验,所以很有可能当我尝试google整个事情时,我只是不知道我在寻找什么。

这就是它的样子:

<entry>
    <id>16</id>
    <link href="/ws/1/h/all/16/" type="application/vnd.m.h+xml" title="m_h_title" />
    <published>2013-05-11T20:53:31.144957Z</published>
    <updated>2013-05-27T12:20:13.963730Z</updated>
    <author>
        <name>Discovery</name>
    </author>
    <title>m_h_title</title>
    <summary>
         A presentation of the substance of a body of material in a condensed form or by reducing it to its main points; an abstract.
    </summary>
    <myns:fields>
      <myns:field name="field_one"   type="xs:string" value="value_one"   /> 
      <myns:field name="field_two"   type="xs:string" value="value_two"   /> 
      <myns:field name="field_three" type="xs:string" value="value_three" /> 
      <myns:field name="field_four"  type="xs:string" value="value_four"  /> 
      <myns:field name="field_five"  type="xs:string" value="value_five"  /> 
    </myns:fields>
</entry>

就我所做的而言......(在我发布之前,这有点简化了)

$output = new SimpleXmlElement($response['data']); 

foreach ($output->entry as $entry) 
{ 
   $arr['id'] = (string) $entry->id;            // this is fine

   $arr['summary'] = trim($entry->summary);     // this is also fine

   print "\$entry->fields type: " . gettype($entry->fields);   // object


   foreach ($entry->fields as $field)   // this doesn't do anything, though 
   {
      $name  = (string) $field['name']; 
      $value = (string) $field['value']; 

      print "$name: $value <br/>";

      $arr[$name] = $value;  
   }  
}

如果我是var_dump $ arr,它确实为ID和摘要保存了正确的值,但我似乎无法获得实际字段中的任何数据。我将继续玩这个...所以,如果没有人回应一分钟,我可能最终更新这个帖子一百万次添加“这是我尝试过的”代码。


以此结束:

 $output = new SimpleXmlElement($xml_response); 

 foreach ($output->entry as $entry) 
 {       
    $arr['id'] = (string) $entry->id; 
    $arr['summary'] = trim($entry->summary);  

     foreach($entry->children('myns', true) as $fields)       // myns:fields
     {       
        foreach ($fields->children('myns',true) as $field)    // myns:field 
        {   
           $name  = (string) $field->attributes()->name;
           $value = (string) $field->attributes()->value;

           $arr[$name] = $value;    
        } 
     }   
  }

1 个答案:

答案 0 :(得分:0)

您需要考虑名称空间,这里没有足够的信息为您提供工作示例 - 但请查看SimpleXMLElement::children处的评论#2。

实际上,这是一个简单的例子。

<?php
$xml = '<items xmlns:my="http://example.org/">
    <my:item>Foo</my:item>
    <my:item>Bar</my:item>
    <item>Bish</item>
    <item>Bosh</item>
</items>';

$sxe = new SimpleXMLElement($xml);

foreach($sxe->item as $item) {
    printf("%s\n", $item);
}

/*
    Bish
    Bosh
*/

foreach($sxe->children('my', true) as $item) {
    printf("%s\n", $item);
}

/*
    Foo
    Bar
*/

安东尼。