在 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;
}
}
}
最佳答案
您需要考虑命名空间,这里没有足够的信息为您提供一个工作示例 - 但请查看 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
*/
安东尼。
关于php - 使用 PHP 通过 SimpleXML 解析 XML 并遇到命名空间问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16862179/