SAN FRANCISCO — Hot-hitting rookie Joe Panik played a key role in a game-tying, four-run rally and started the game-deciding rally as the Giants beat the Phillies, 6-5, on Saturday.

Panik’s infield single in the sixth cut the Phillies’ lead to 5-3. He lined a triple into the right-center field gap to start the eighth and scored on a Gregor Blanco single to break a 5-5 tie.

In the process, the Giants won for only the second time in eight games and cut the Los Angeles Dodgers’ lead in the National League West to 4½ games.

Jeremy Affeldt and Sergio Romo combined for the final three outs to close out the victory.

Hunter Pence staked the Giants to a 1-0 lead with a home run with one out in the first inning. For Pence, that marked his 16th home run of the season.

The Phillies finally got to Giants starter Tim Hudson in the third. Jimmy Rollins walked and Chase Utley singled with one out. Rollins scored on a Ryan Howard single, Utley made it 2-1 when he scored on a Marlon Byrd sacrifice fly.

The Giants wasted an opportunity to tack on another run when they failed to bring home Michael Morse, who led off the second with a triple.

The Phillies jumped to a sizable lead in the fifth. The first four batters reached off Hudson. Howard’s two-run single made it 5-1, knocked Hudson from the game and placed the scuffling Giants in a huge hole.

But the Giants rallied in the sixth. The uprising began with a Buster Posey single, a Phillies error that allowed Pablo Sandoval to reach and a Morse RBI double. That cut the deficit to 5-2, sent Phillies starter Kyle Kendrick to the bench and brought the potential tying run to the plate with no outs.

Panik made it 5-3 with an infield hit on a chopper off the plate. Pinch-hitter Blanco flared a single to left to make it a one-run game. Angel Pagan’s sacrifice fly tied the game.