The world number one, who failed to retain his Australian Open crown earlier this year, was 5-4 and 30-15 down in the third set before his opponent, ranked 137th by the ATP, crumbled under the pressure.
Second-seeded claycourt king Rafael Nadal, bidding for a fourth consecutive title in the principality, never let Mario Ancic into their match, powering to a 6-0, 6-3 win over the Croatian in 75 minutes.
He next faces compatriot Juan Carlos Ferrero, who beat Finn Jarkko Nieminen 6-3, 6-3, while Federer meets Frenchman Gael Monfils, who beat Croatia's Ivo Karlovic 7-6, 6-1.
Ferrer cruises
There was no scare for Spanish fifth seed David Ferrer, who eased past former world number one Marat Safin 6-2, 6-3 to set up a third-round encounter with Serb Janko Tipsarevic, a narrow 5-7, 7-6, 6-4 winner over a battling Nicolas Lapentti of Ecuador.
Safin's compatriot Nikolay Davydenko, seeded fourth, held off a late challenge by Italian Simone Bolelli to go through with a 6-2, 7-6 win. Davydenko will take on German Philipp Kohlschr-eiber, who beat his compatriot Nicolas Kiefer 6-2, 6-4.
On centre court, Federer took a one-sided first set in 31 minutes but Ramirez Hidalgo opened 4-0 lead in the second, hung on to it and trapped his opponent into a decider.
The Swiss went 4-0 down again but this time Ramirez Hidalgo was caught out by the pressure.
France's Richard Gasquet, who suffered back pain after Tuesday's training, was back to his best in a 6-1, 6-2 drubbing of Belgian qualifier Kristof Vliegen.
The seventh seed will face Sam Querrey for a quarterfinal spot after the American beat Italian Andreas Seppi 6-1, 7-5. Russia's Igor Andreev and Nicolas Almagro of Spain will meet in the third round after they benefited from the retirements of their opponents, respectively Russian Mikhail Youzhny and Argentine Juan Monaco.
Paes-Hanley exit
Meanwhile, India’s Leander Paes and his Australian partner Paul Hanley crashed out of the doubles competition.
They went down to the second-seeded Israeli duo of Jonathan Erlich and Andy Ram in three sets 6-4, 3-6, 3-10.