2013-05-31 100 views
1

SO和PHP.net有很多关于使用PHP来处理XML的信息,但我有问题找到任何显示如何使用命名空间我的XML的设置方式也是如此。我对XML没有经验,所以当我尝试谷歌整个事情时,我完全不知道我在找什么。使用PHP解析XML与SimpleXML和命名空间的问题

这是什么样子:

<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;  
     } 
    } 
    } 

回答

0

你需要考虑到的命名空间,有没有足够的信息,这里为你提供工作的例子 - 但看看评论# 2在SimpleXMLElement::children

其实,这里有一个简单的例子。

<?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 
*/ 

安东尼。

+0

我不能让它工作 - 你可以切换它,以便具有命名空间的字段在/没有命名空间的字段中/在吗? like' foo酒吧' –