The 60th-ranked Lopez won the first set in 24 minutes, firing 11 winners in a dazzling display of serving and sharply angled groundstrokes, but the Swiss maestro stepped up several gears to win their fourth-round match 3-6 6-4 6-1 6-4.
In the quarterfinals, Federer will play 2003 champion Roddick, the man he beat in last year's final, who was leading 7-6 2-0 when ninth-seeded Czech Tomas Berdych retired with nausea and breathing problems in their fourth-round clash.
The American said he felt sorry for Berdych but with a world number one Federer waiting in the wings, he added: "This is a lot better than being dead tired."
Also advancing were fourth seed Nikolay Davydenko of Russia and 10th-seeded Tommy Haas of Germany.
On the women's side, winners included Russians Svetlana Kuznetsova and Anna Chakvetadze, and Israeli upstart Shahar Peer.
MONUMENTAL UPSET
The 25-year-old Lopez played as well as he could during the first two sets, causing the 23,000 in Arthur Ashe Stadium to squirm in anticipation of a monumental upset.
"He was dictating play, he was serving unbelievable," said Federer. "You always hope he's not going to continue to play that well and you try to find something positive.
"It was definitely a struggle. I was fortunate. I played great in the end."
Federer committed just 12 errors during the 199 points played in the two-hour match. Lopez had 22 winners in the first two sets but only 12 thereafter.
Fourth seed Kuznetsova needed only 74 minutes to dispose of awe-struck Victoria Azarenka of Belarus 6-2 6-3 to reach the Open's last eight for the first time since winning the title in 2004.
"I feel like I'm getting better every match," said Kuznetsova, the highest remaining seed in the bottom half of the draw. "I'm very confident about my game."
Chakvetadze had 23 errors during a second-set wobble but defeated Austrian Tamira Paszek 6-1 7-5.
Haas upset sixth-seeded American James Blake 4-6 6-4 3-6 6-0 7-6, winning the tiebreaker 7-4, while Davydenko continued his march through the draw with a 6-1 6-3 6-4 rout of South Korea's Lee Hyung-taik.
Davydenko, who will face Haas in the quarters, has not lost a set during his four Open matches.