PHP循环通过XML嵌套循环,而不使用多个foreach循环?
是否有更干净的方法来实现这一点: XML是:PHP循环通过XML嵌套循环,而不使用多个foreach循环?,php,xml,simplexml,Php,Xml,Simplexml,是否有更干净的方法来实现这一点: XML是: <Specifics> <Name> <Type>Brand</Type> <Value>Apple</Value> <Source>list</Source> &l
<Specifics>
<Name>
<Type>Brand</Type>
<Value>Apple</Value>
<Source>list</Source>
</Name>
<Name>
<Type>Country</Type>
<Value>USA</Value>
<Source>list</Source>
</Name>
<Name>
<Type>Rating</Type>
<Value>87</Value>
<Source>list</Source>
</Name>
<Name>
<Type>Project</Type>
<Value>Dolphin</Value>
<Source>list</Source>
</Name>
<Name>
<Type>Age</Type>
<Value>10-20</Value>
<Source>list</Source>
</Name>
</Specifics>
您可以使用Xpath。如果我理解正确,您希望迭代
name
元素并从其子元素读取数据。SimpleXML对xpath的支持也很有限。但是我更喜欢直接使用DOM
$dom = new DOMDocument();
$dom->loadXml($xml);
$xpath = new DOMXpath($dom);
// iterate all `Name` elements anywhere in the document
foreach ($xpath->evaluate('//Name') as $nameNode) {
var_dump(
[
// fetch first `Type` element in $nameNode and cast it to string
$xpath->evaluate('string(Type)', $nameNode),
$xpath->evaluate('string(Value)', $nameNode),
$xpath->evaluate('string(Source)', $nameNode)
]
);
}
和ThW一样,我还要说xpath是访问细节/名称的方法。当您标记这个simplexml时,在您的案例中还有一些简短的方法来获取命名值:
foreach ($xml->xpath('/*//Specifics/Name') as $name)
{
print_r(array_map('strval', iterator_to_array($name)));
}
输出:
Array
(
[Type] => Brand
[Value] => Apple
[Source] => list
)
Array
(
[Type] => Country
[Value] => USA
[Source] => list
)
Array
(
[Type] => Rating
[Value] => 87
[Source] => list
)
Array
(
[Type] => Project
[Value] => Dolphin
[Source] => list
)
Array
(
[Type] => Age
[Value] => 10-20
[Source] => list
)
可以使用递归迭代每个元素及其子元素。
Array
(
[Type] => Brand
[Value] => Apple
[Source] => list
)
Array
(
[Type] => Country
[Value] => USA
[Source] => list
)
Array
(
[Type] => Rating
[Value] => 87
[Source] => list
)
Array
(
[Type] => Project
[Value] => Dolphin
[Source] => list
)
Array
(
[Type] => Age
[Value] => 10-20
[Source] => list
)