在 SO 和 PHP.net 上有很多关于使用 PHP 处理 XML 的信息,但是我在查找任何显示如何以与我的 XML 设置方式相同的方式使用命名空间的内容时遇到问题。我根本没有使用 XML 的经验,所以当我尝试用谷歌搜索整个事情时,我很可能只是不知道我在寻找什么。
这是它的样子:
<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;
}
}
}