Sorin Pascan Sorin Pascan - 2 months ago 12
PHP Question

PHP SimpleXML not parsing <

For some reason SimpleXML is not parsing

<ADMIN>
.

My XML file contents:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE client-config SYSTEM "asigra_conf_windows.dtd">
<notifications>
<email-notification recipient="&lt;ADMIN&gt;"/>
</notifications>


Code that reads the XML file:

$xml = simplexml_load_file('http://localhost/test/xml.xml');

echo "Recipient:". $xml['email-notification']['@attributes']['recipient'];


Output is Recipient: "blank"

How can I make it read the ADMIN from
&lt;ADMIN&gt;
?

I'm using xampp with Apache and PHP 5.6.

Answer

Thank you everybody for you assistance (especially IMSoP, you were right about htmlspecialchars).

The reason I kept failing was because I was reinforcing the stereotype of man not reading the manual.

I just had to spend 5 minutes looking at the examples @ http://php.net/manual/en/simplexml.examples-basic.php. It also explains why you should not use json_encode/decode.

For other tl;dr people, here are some examples of the code that I am using now:

When I have XML that looks like this:

<configuration>
    <setup-config>
        <account-name>Trump</account-name>
    </setup-config>
<configuration>

$xml = simplexml_load_file('http://localhost/config.xml');

echo $xml->{'configuration'}->{'setup-config'}->{'account-name'};

 

When I have XML that looks like this:

<configuration>
    <setup-config>
        <user-info country-code="826"/>
    </setup-config>
<configuration>

$xml = simplexml_load_file('http://localhost/config.xml');

echo $xml->{'configuration'}->{'setup-config'}->{'user-info'}['country-code'];

 

When I have XML with HTML chars:

<configuration>
    <defaults-config>
        <def-notification name="&lt;ADMIN&gt;"/>
    </defaults-config>
</configuration>

$xml = simplexml_load_file('http://localhost/config.xml');

echo htmlspecialchars($xml->{'configuration'}->{'defaults-config'}->{'def-notification'}['name']);

 

Iterating:

<configuration>
    <roles-config>
        <group-role role="administrator" name="Administrators" from="."/>
        <group-role role="backup-operator" name="Backup Operators" from="."/>
    </roles-config>
</configuration>

$xml = simplexml_load_file('http://localhost/config.xml');

foreach ($xml->{'configuration'}->{'roles-config'}->{'group-role'} as $grouproles => $groles) {
    echo "<tr><td>group role name: ".$groles['name']."</td></tr>";
    echo "<tr><td>group role role: ".$groles['role']."</td></tr>";
    echo "<tr><td>group role role: ".$groles['from']."</td></tr>";
}

 

Simple existence check:

<configuration>
    <setup-config>
        <account-name>Trump</account-name>
    </setup-config>
<configuration>

$xml = simplexml_load_file('http://localhost/config.xml');

if(isset($xml->{'configuration'}->{'setup-config'}->{'account-name'})){
    echo $xml->{'configuration'}->{'setup-config'}->{'account-name'};
}