我想通过PHP从REST XML文件中获取方法。 我有本地REST文件,格式为:
SimpleXMLElement Object
(
[doc] => SimpleXMLElement Object
(
)
[resources] => SimpleXMLElement Object
(
[@attributes] => Array
(
[base] => https://**url**
)
[resource] => Array
(
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[path] => xml/{accesskey}/project
)
[param] => SimpleXMLElement Object
(
[@attributes] => Array
(
[name] => accesskey
[style] => template
[type] => xs:string
)
)
[method] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => getAllProjects
[name] => GET
)
[response] => SimpleXMLElement Object
(
[representation] => SimpleXMLElement Object
(
[@attributes] => Array
(
[mediaType] => application/xml; charset=utf-8
)
)
)
)
... and so on
我有以下代码,但它只返回第一个方法名称:
$file="application.wadl";
$xml = simplexml_load_file($file);
foreach($xml->resources[0]->resource->method->attributes() as $a => $b) {
echo $b,"\n";
}
我想提取所有这些,而不仅仅是第一个。怎么做?
答案 0 :(得分:1)
不是循环遍历一个元素的属性,而是需要遍历所有具有相同名称的元素。由于SimpleXML的神奇之处,这很简单:
foreach($xml->resources->resource->method as $method) {
echo $method['id'],"\n";
}
当跟随另一个运算符时,与->resources
一样,SimpleXML假设您只想要具有该名称的第一个元素。但是如果你循环,它会给你们每一个,作为一个SimpleXML对象。
编辑:看起来XML的嵌套意味着您需要某种形式的递归(您需要查看$xml->resources->resource->resource->resource->method
等)。
这样的事情(未经测试的例子)?
function get_methods($base_url, $node)
{
$all_methods = array();
// Child resources: build up the path, and recursively fetch all methods
foreach ( $node->resource as $child_resource )
{
$child_url = $base_url . '/' . (string)$child_resource['path'];
$all_methods = array_merge(
$all_methods,
get_methods($child_url, $child_resource)
);
}
// Methods in this resource: add to array directly
foreach ( $node->method as $method )
{
$method_url = $base_url . '/' .(string)$method['id'];
$all_methods[$method_url] = (string)$method['id'];
}
return $all_methods;
}
print_r( get_methods('/', $xml->resources) );
顺便说一下,print_r
并不总能为您提供SimpleXML对象的最佳视图,因为它们实际上是非PHP代码的包装器。请改为this simplexml_dump()
function。