PHP: Get Latest Google Library Snippet

If you use JavaScript libraries, you most likely use Google’s Hosted Libraries to better and faster serve visitors. These libraries are constantly being updated, and therefore the code snippets you use in your web applications become deprecated rather quickly.

In this tutorial, we’ll create a PHP function that dynamically gets the code snippet from Google each time a page loads so that you never have to update this part of your pages (unless Google changes the HTML layout).

If you’d just like the code, scroll to the end of the tutorial.

In order to use this function, you will need:

  • The permission to use file_get_contents() or a substitute
  • The DOMDocument class (usually included)

Before we create our function, let’s take a look at how Google formats their HTML:

<div id="jquery">
<dl>
<dt>jQuery</dt>
<dd>
<strong>snippet:</strong>
<code class="snippet">&lt;script
src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"&gt;&lt;/script&gt;</code>
</dd>
<dd>
<strong>site:</strong>
<a href="http://jquery.com/" target="_blank">http://jquery.com/</a>
</dd>
<dd>
<strong>versions:</strong>
<span class="versions">1.8.3, 1.8.2, 1.8.1, 1.8.0, 1.7.2,
1.7.1, 1.7.0, 1.6.4, 1.6.3, 1.6.2, 1.6.1, 1.6.0, 1.5.2,
1.5.1, 1.5.0, 1.4.4, 1.4.3, 1.4.2, 1.4.1, 1.4.0, 1.3.2,
1.3.1, 1.3.0, 1.2.6, 1.2.3</span>
</dd>
<dd><strong>note:</strong> 1.2.5 and 1.2.4 are not hosted due to
their short and unstable lives in the wild.</dd>
</dl>
</div>

Example: jQuery

In the above example, you can see that Google has a very organized, standard layout for displaying all of the information about the libraries. This makes it easier for us!

Our very first step, as always, will be to create our function handler. All of the following code will reside inside these handlers.

function get_google_snippet($lib_name) {
}

The function accepts one parameter – the name,  or part of the name, of the library that you need the snippet for.

Because we’ll be searching the library URLs for the library names, we have to replace the spaces with URL-friendly characters.

$lib_name = str_replace(' ', '-', strtolower($lib_name));

Google uses dashes instead of spaces in its URLs. The reason for strtolower() in the above line is that Google also uses lowercase letters (ex: jquery-ui.min.js). The only exception is Chrome Frame Install. To add an exception rule for this library, please wait for the end of the tutorial.

Now that we have the library name, we need the contents of Google’s webpage:

$page_contents = file_get_contents('https://developers.google.com/speed/libraries/devguide');

We can use PHP’s DOMDocument class to get the content we want from the above HTML. So, let’s create a new instance of that class and load our HTML.

$dom = new DOMDocument;
@$dom->loadHTML($page_contents);

The apetail (@) at the start of line 2 tells PHP that we don’t want errors returning from this line of code. If there happen to be errors in Google’s HTML, loading the HTML would normally return a PHP warning.

Next, we’ll use the DOMDocument function getElementsByTagName() to get all the <code> HTML tags. Google stores the URLs in these tags. Since this method returns an array of objects, we’ll use foreach loop afterwards to cycle through each element of the array.

$codes = $dom->getElementsByTagName('code');
foreach ($codes as $code_tag) {
}

Everything from now on will be inside the foreach loop.

In case Google has more <code> tags in its page, we want to ferret out the ones holding code snippets. These ones have the class “snippet”, so we can check for that:

if ($code_tag->getAttribute('class') == 'snippet') {
}

In the above line, we ensure that the code tag has a class attribute of “snippet” before continuing.

Now, we simply have to check if the library name entered as a parameter at the beginning is part of the snippet. Inside the above if statement,

if (strpos($code_tag->nodeValue, $lib_name) !== false) {
}

$code->nodeValue gets the content of the code tag, ignoring other attributes of the tag. The strpos() function returns the position of the search substring in the haystack, or false if it doesn’t exists. We want to make sure it exists.

Lastly, return the snippet, removing excess spaces

return preg_replace('/\s+/', ' ', $code_tag->nodeValue );

In order to remove replace two or more spaces with just one, we use the preg_replace() function, which uses regular expressions. These are too complex to explain in this tutorial, please do your own research on this subject. If you are aware of regex, the \s+ checks for whitespace.

The Chrome Frame Install Exception

If you don’t use Chrome Frame, or have never heard of it, you can ignore this section.

After this line in our function:

$lib_name = str_replace(' ', '-', strtolower($lib_name);

Add the following if block:

if (strpos($lib_name, 'chrome') !== false) {
$lib_name = 'CFInstall';
}

Since Google’s Chrome Frame Install (CFI) URL has capital letters and is abbreviated, our default code would not return the proper snippet. With this rule, our method will work excellently.

Testing Our Code

In order to ensure that our function works properly, just use the following lines:

echo get_google_snippet('jquery') . "\n" . get_google_snippet('prototype');

Since the snippets are HTML code, you won’t actually see the snippets. However, if you view the page’s source, you will see the two <script> tags.

That’s it! I hope you enjoyed the tutorial or this at least comes to some use for you. If you have questions, drop a comment below!

Here is the entire function as one block (without CFI exception):

function get_google_snippet($lib_name) {
  $lib_name = str_replace(' ', '-', strtolower($lib_name));
  $page_contents = file_get_contents('https://developers.google.com/speed/libraries/devguide');
  $dom = new DOMDocument;
  @$dom->loadHTML($page_contents);
  $codes = $dom->getElementsByTagName('code');
  foreach ($codes as $code_tag) {
    if ($code_tag->getAttribute('class') == 'snippet') {
       if (strpos($code_tag->nodeValue, $lib_name) !== false) {
          return preg_replace('/\s+/', ' ', $code_tag->nodeValue );
       }
    }
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>