I have a simple XML response I'm receiving into a variable ($response):
<tsresponse xmlns="http://tableau.com/api" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation="http://tableau.com/api http://tableau.com/api/ts-api-3.7.xsd">
<pagination pagenumber="1" pagesize="100" totalavailable="1">
<users>
<user externalauthuserid="" id="abcd1234-hijk-lmno-1234-abcd9876" name="TestUsername" siterole="Explorer">
</user>
</users>
</pagination>
</tsresponse>
I am trying to retrieve the value of "id".
$xml=simplexml_load_string($response) or die("Error: Cannot create object");
$tableauuserid = $xml->pagination->users[0]->user['id'];
echo "The (existing) Tableau User ID is: ". $tableauuserid;
The (mostly) same format works for a level up where I'm retrieving the value of id in a similar response - except then I'm just dealing with "user" and not "pagination->users->user". Currently the variable $tableauuserid is empty.
Any ideas on how I can retrieve the value of id?
A simple way to find any <user>
element would be to use XPath. The only slight complication is the default namespace defined on the base element. To get round this you need to register that namespace (using registerXPathNamespace()
) and then use the prefix as part of the name.
Calling xpath()
will return a list of matching nodes, so you need to use [0]
to use the first one...
$xml->registerXPathNamespace("d", "http://tableau.com/api");
$user = $xml->xpath("//d:user[@id]");
$tableauuserid = $user[0]['id'];