I would like to get methods from REST XML file via PHP.
I have local REST file, which is in this format:
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
I have the following code, but it returns just the first method name:
$file="application.wadl";
$xml = simplexml_load_file($file);
foreach($xml->resources[0]->resource->method->attributes() as $a => $b) {
echo $b,"\n";
}
I would like to extract all of them, not just the first one. How to do that?
Rather than looping over the attributes of one element, you need to loop over all the elements with the same name. Due to the magic of SimpleXML, this is as simple as this:
When followed immediately by another operator, as with
->resources, SimpleXML assumes you just want the first element with that name. But if you loop over, it will give you each of them, as a SimpleXML object.EDIT : It looks like the nesting of your XML means you need some form of recursion (you need to look at
$xml->resources->resource->resource->resource->methodetc).Something like this perhaps (untested example)?
Incidentally,
print_rwon’t always give you the best view of a SimpleXML object, because they are actually wrappers around non-PHP code. Try thissimplexml_dump()function instead.