Tips and tricks for LAMP (Linux Apache MySQL PHP) developers.

When I cant find a suitable solution to a problem and have to work it out for myself I'll post the result here so hopefully others will find it useful. (All code is offered in good faith. It may not be the best solution, just a solution).

Thursday, 20 November 2014

SimpleXML and mixed, nested namespaces

I work with several third party marketplace APIs, one of which is Amazon's MWS API.
When processing their GetMatchingProductForId response I discovered that they sometimes namespace the XML nodes (with ns2).

PHP's SimpleXML doesn't allow access to namespaced nodes via the usual interface of $simpleXml->node but I found you can specify a namespace to the children() method like so:

$simpleXml
    ->children('ns2', true)
    ->namespacedNode

That works great but then I hit a problem. As I mentioned, Amazon namespace some of the nodes but not all and the node I was really after was not namespaced itself but was a child of a namespaced node. After I applied the code above I found that I couldn't access the child node:

$simpleXml
    ->children('ns2', true)
    ->namespacedNode
    ->nonNamespacedNode

I thought all was lost until I discovered you can reset SimpleXML's namespace filter back to none again with another call to children() so you can get at the non-namespaced child node:

$simpleXml
    ->children('ns2', true)
    ->namespacedNode
    ->children()
    ->nonNamespacedNode

Sunday, 29 June 2014

Jasmine and Jasq

Recently I've started using Jasmine - a BDD framework - to test some pretty complex JavaScript I've been writing for work. We're using RequireJS for our JavaScript and we found a great plugin for Jasmine to make it play nicely with AMD modules called Jasq.

All works beautifully except for one thing: the Jasq docs say to wrap your specifications in a require block but that didn't seem to work for me. Once I changed them to define blocks (see below) everything started working. I don't know why this is and it doesn't seem anyone else had the same issue so perhaps I've done something wrong but I just thought I'd put this out there in case anyone else runs into the same issue.

define(['jasq'], function ()
{
  describe('My Tests', 'thing/to/test', function()
  {
    it('should do something', function(thingToTest)
    {
        //...
    });
  });
});