This site is no longer active and is available for archival purposes only. Registration and login is disabled.

Stupid programmer tricks


Stupid programmer tricks

Postby Dan East » May 6, 2010 @ 5:31pm

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
User avatar
Dan East
Site Admin
 
Posts: 5264
Joined: Jan 25, 2001 @ 5:19pm
Location: Virginia, USA


Re: Stupid programmer tricks

Postby sponge » May 6, 2010 @ 10:30pm

I think this is why they say "never match XML with regexs"
holy internets batman.
User avatar
sponge
Not sponge
 
Posts: 12779
Joined: Jan 13, 2002 @ 8:04am
Location: New Hampshire


Return to General


Sort


Forum Description

General development discussion including business/marketing topics. Platform-specific discussion should be placed in the appropriate forum below.

Moderators:

Dan East, sponge, Digby, David Horn, Kevin Gelso, RICoder

Forum permissions

You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum