Lewis Lebentz
Lewis Lebentz

Reputation: 885

How can I format XML?

I have worked out how to cURL the JSS Casper API in PHP, and receive a response in XML. In the browser, it just formats everything without any whitespace on one line. Here is a sample of the XML:

<accounts>
  <users>
    <user>
      <id>1</id>
      <name>administrator</name>
    </user>
  </users>
  <groups>
    <group>
      <id>2</id>
      <name>Example Group</name>
      <site>
        <id>-1</id>
        <name>None</name>
      </site>
    </group>
  </groups>
</accounts>

How can I format this into a HTML table or something prettier? Is there a simple way of converting it?

Here is the code I tried:

<?php
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, "https://example.jamfcloud.com/JSSResource/accounts");
    curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($curl, CURLOPT_USERPWD, "user:pass");
    $result = curl_exec($curl);
    curl_close($curl);

    $arr = simplexml_load_string_($curl);
    $xml = $arr->member;
?>
<table>
    <tr>
        <th>User</th>
        <th>ID</th>
        <th>Name</th>
    </tr>
    <?php foreach($xml as $row) { ?>
        <tr>
            <td><?php echo $row->user ?></td>
            <td><?php echo $row->id ?></td>
            <td><?php echo $row->name ?></td>
        </tr>
    <?php } ?>
</table>

Upvotes: 0

Views: 66

Answers (1)

rgajrawala
rgajrawala

Reputation: 2188

You are calling simplexml_load_string wrong:

$arr = simplexml_load_string_($curl);

should actually be:

$arr = simplexml_load_string($result);


Remove

$xml = $arr->member;

since you can just replace the foreach loop like:

<?php foreach($arr->users->user as $row) { ?>

See this answer.

Upvotes: 1

Related Questions