The loss snapped Washington's seven-game winning streak and the Nationals fell 5? games behind the Reds (winners in Milwaukee) for the second NL wild card.
Washington scored three in the seventh to pull within 5-4.
Cole Hamels (8-13) won his fourth straight decision, allowing four runs, three earned, on eight hits in six-plus innings. Jonathan Papelbon survived a leadoff double in the ninth for his 27th save.
Washington's Denard Span (3 for 5) extended his hitting streak to 25 games and stole a career-high three bases.
Gio Gonzalez (10-7), coming off a one-hitter against the Mets, allowed four runs on nine hits in six innings.
Pinch-hitter Scott Hairston, Span and Ryan Zimmerman singled to load the bases in the seventh and end Hamels' night.
Facing Justin De Fratus, Jayson Werth grounded to third and Cody Asche threw home for the out. Ian Desmond plated Span with a sacrifice fly to make it 5-2.
Left-hander Cesar Jimenez came in to pitch to Bryce Harper and Harper blooped a single to center scoring Zimmerman. When center fielder Cesar Hernandez overran the ball, Harper went to second and Werth scored from first.
B.J. Rosenberg fanned Wilson Ramos for the third out.
Philadelphia took the lead in the fifth. With one out, Mayberry hit an 0-1 offering from Gonzalez into the visitors' bullpen to tie the score.
The Phillies weren't done as Hamels and Hernandez followed with singles. Jimmy Rollins flied out, but Chase Utley walked to load the bases. After pitching coach Steve McCatty visited Gonzalez, Ruiz hit the left-hander's first pitch over Werth's head in right for a bases-clearing double.
Since Aug. 8, Ruiz is batting .583 (14 for 24) with runners in scoring position, with six doubles and 19 RBIs.
Utley added an RBI-single in the seventh to make it 5-1.
Washington took the lead in the first. Span singled, stole second, went to third on a wild pitch and scored on Werth's sacrifice fly.