Search code examples
arraysapipacketplesk

How do I return a Plesk API XML package into an array


I am using plesk api to return informaton from plesk. It gets put into an xml string eg

$response = $client->request($request);

The string has this information in

<database>
<get-db>
<result>
<filter-id>domain name</filter-id>
<id>34</id>
<name>database</name>
<type>mysql</type>
...etc snip
</result>
<result>
<filter-id>domain name</filter-id>
<id>36</id>
<name>database</name>
<type>mysql</type>
...etc snip
</result>
</get-db>
</database>

What I want to put the result into a 2 dimensional array.

I want the first to be name and I also need the id

I have tried using preg_match to get the tags, but for some reason I am only getting the first tag. And of course the function isn't putting it inside a 2 dimensional array yet.

function tags($string, $tagname)
{
    $pattern = "#<\s*?$tagname\b[^>]*>(.*?)</$tagname\b[^>]*>#s";
    preg_match($pattern, $string, $matches);
    return $matches;
}

This is so I can match the name and get the id you see.

I am editing because I have just found something that might help, but I haven't worked it out yet

$xml=simplexml_load_string($response) or die("Error: Cannot create object");

I think this is for parsing xml, but can't seem to get it parse my xml package properly.

Also tried this

$data = simplexml_load_string($response);
echo $data->result[0]->name;

But this doesn't seem to work.


Solution

  • I have solved this now

    $response = $client->request($request); // Send query to Plesk host
    echo $response; // show response
    
    $xml = simplexml_load_string($response);
    
    
    echo $xml->database->{'get-db'}->result[0]->name;
    // This gets the first tag called name
    
    //This loops through and gets every tag called name
    foreach ($xml->database->{'get-db'}->result as $result)
    {
       echo '<pre>'.$result->name.'</pre>';
    //If I want to now I can put this result into an array here, but I find I do not need to now. As I only want to find the id of a matched database. So no array needed now, as I can use this loop
    }