Page 1 of 1

Stupid programmer tricks

PostPosted: May 6, 2010 @ 5:31pm
by Dan East
I just wasted an hour on something really stupid. I was working on PHP code that retrieves an extremely simple XML document from another website and parses it using standard expressions. The XML just had a single value, a floating point number. So whenever I tried to do any math against the value I parsed I would always get 0. Even just casting it to a double or float would return a 0. Whenever I echoed the contents of the parsed value I would see the proper numerical value, just as expected.

So after goofing around for a long time I finally realized my mistake. PHP's preg_match_all returns an array of matches, and the first element is the entire string that was to be parsed. I was using that as my parsed value, which was my error. Here's the rub - since it was XML, when I dumped the value, the web browser would hide all the XML tags, so all I saw was just the numeric value itself. Of course PHP couldn't convert that mess to a floating point number, so it always resulted in 0 when cast to a number.

If I had been dealing with more complex XML, containing more than one entity, it would have been obvious immediately. So the simplicity of that data is what helped hide my error.

Anyway, I thought I would share that little bit of stupidity with everyone...

Dan

Re: Stupid programmer tricks

PostPosted: May 6, 2010 @ 10:30pm
by sponge
I think this is why they say "never match XML with regexs"