Lopez, seeded 30th at Flushing Meadows, turned in an impressive performance, and having been shaded in two tough sets settled by tie-breaks, he had his chance when Murray appeared to wilt in the New York heat.
The temperature was 32C in the heat of the afternoon, and Lopez, who had come through a five-setter in the previous round, looked the fresher player, breaking Murray late to take the third set and keep the Scot on court.
There was no call to the trainer from the world number four, nor any of the histrionics some associate with Murray as he negotiated the fourth set.
He had to fend off break points, and served around 10mph slower than he had done in the opening two sets, but produced some inspired tennis in the tie-break to get from 4-3 down to reel off the last four points and win in just shy of four hours.
"I was struggling a little bit physically," Murray said afterwards.
"It's the last major event of the year and you want to push through anything physically, so I'll be out for the next round giving it 100 per cent for sure."
Murray will next face 15th seed Milos Raonic, after the Canadian overcame home favourite James Blake 6-3 6-0 7-6(3).
Raonic made a blistering start to the match, comfortably out-playing Blake from every area of the court.
But buoyed by the home crowd Blake bounced back in the third, timing his run in form along with a dip from Raonic as the Canadian hit his first double fault, quickly followed by his second and third.
After finding himself a break down early on, Blake bounced back and it even looked possible he might grab a second break push the match to a fourth set.
But Raonic once again found his serve, holding on to force the tie-break before running away with it to set up the meeting with the world number four.