Technology

PHP: Is SimpleXML Loaded?

There are a couple plugins that I’ve built that require PHP5+ and SimpleXML. SimpleXML is a much easier and better performing method of parsing XML responses from APIs. The problem, though, is that I would get at a few emails a day or week asking me why the user couldn’t load the program and it resulted in errors.

Apparently, my notices on the plugins and on the project pages weren’t enough, so I did the right thing and added functionality to both plugins to verify the SimpleXML extension is loaded.

PHP Function to check the SimpleXML extension is loaded:

function isSimpleXMLLoaded() {
$array = array();
$array = get_loaded_extensions();
$result = false;
foreach ($array as $i => $value) {
if (strtolower($value) == "simplexml") { $result = true; }
}
return $result;
}

Now, within the functions that use SimpleXML, I can simply ensure it’s loaded before I actually try the SimpleXML call. If

if (!isSimpleXMLLoaded()) {
echo "Host your site somewhere else!";
return;
}

I know I’ve got some PHP gurus that keep an eye on my blog, let me know how I did! I’ve released minor updates to both Plugins to utilize this method.

6 Comments

  1. 1

    Hi Doug,

    I did notice a one bug which probably doesn’t raise an error.

    if ($value = “SimpleXML”) { $result = true; }

    should be

    if ($value == “SimpleXML”) { $result = true; }

    Although for safety sake. I prefer.

    if (strtolower($value) == “simplexml”) { $result = true; }

    You could also use ‘extension_loaded’ which takes the extension name to check (case sensitive).

    $loaded = extension_loaded(“SimpleXML”);

    Returns TRUE or FALSE.

    P.S. Don’t drink coffee myself but I may put a ‘buy me a box of donuts’ button 🙂

    • 2

      Get that donut button up, Nick! You’re a livesaver! What’s funny is that (minus the strtolower), I actually did have my sample code running and utilizing the right evaluation. It must have been late because by the time I put it in, I messed it up!

      I’ve modified the code and the blog post. Question: Any advantage of one over the other? I guess the extension_loaded is a much cleaner and quicker way of dealing with this!

      Thanks Nick!

  2. 4

    yum install php55-xml.x86_64 to install simpleXML for php 5.5.11

    Running Transaction
    Installing : php55-xml-5.5.11-1.el6.x86_64 1/1
    Verifying : php55-xml-5.5.11-1.el6.x86_64 1/1

    and then it installed
    /usr/lib64/php/modules/simplexml.so

  3. 5

Leave a Reply