The decisive rally included a two-run triple by Ryan Howard and two-run homer by National League home run leader Domonic Brown.
Hamels (2-9) snapped a personal six-start losing streak as the Phillies, who have won their last four, broke a 1-1 tie in the seventh when Hamels was lifted for a pinch-hitter.
He hadn't recorded a win since April 28 and was the pitcher of record in his next six starts -- all losses. But Wednesday he allowed four hits and one walk while striking out 11 in a seven-inning outing.
The lone run he allowed came on a Derek Dietrich home run in the fourth inning and tied the score at 1-1. Philadelphia scored first when John Mayberry came around from first on an Erik Kratz two-out double in the second.
Delmon Young, hitting for Hamels, delivered a one-out single in the seventh and Ben Revere followed with another base hit. After another out, Jimmy Rollins singled in one run and Howard tripled in two others. Brown followed with his 18th home run of the season.
All the Phillies' seventh-inning runs came against A.J. Ramos (0-2) in his one inning of relief.