(CNN) -- European champions Spain edged out hosts South Africa 3-2 in extra-time to avoid a second embarrassing defeat and finish third at the Confederations Cup in Rustenburg on Sunday.
Substitute Daniel Guiza, No. 17, fires home his first goal in Spain's 3-2 victory against South Africa.
Midfielder Xavi Alonso netted the winner in the 107th minute when his curling free-kick evaded his own players, the South African defenders and unsighted goalkeeper Itumeleng Khune.
It was a bitter blow for the home fans, whose side had been on the verge of earning a famous victory ahead of the 2010 World Cup, which the country will also host.
What is the Confederations Cup?
After an uninspiring first hour of the match, 'Bafana Bafana' took a shock lead in the 73rd minute through substitute Katlego Mphela.
The striker, who was surprisingly brought on for South Africa's best player, midfielder Steven Pienaar, controlled a left-wing cross by Siphiwe Tshabalala with his knee and stabbed the ball past Iker Casillas in the 73rd minute.
Spain, who suffered a shock 2-0 defeat by the United States in the semi-finals, were frustrated by their star-studded line-up's inability to break down the home team.
Coach Vicente del Bosque withdrew his misfiring strike-force of Fernando Torres and David Villa in the 58th minute, bringing on David Silva and Daniel Guiza.
It was Guiza who turned the match in Spain's favor with two late goals in the space of two minutes.
Firstly he was given time to control the ball inside the penalty area, and fired a low shot past the impressive Khune's despairing right-hand lunge in the 87th minute.
Then Khune, who had kept his team in the match with a string of earlier saves, saw Guiza's cross-shot from the right-hand edge of the penalty area curl over his head and into the net via the post.
However, South Africa were not finished yet, and Mphela sent the crowd into raptures when he smashed a free-kick past Casillas to force extra-time.
Khune saw another Spanish cross, this time from Joan Capdevila, loop over his head and onto the top of the crossbar, while at the other end Casillas denied Mphela his hat-trick with a fine block with his legs.
Spain thought they had a penalty when Silva's header hit the arm of substitute Bhusi Mhlongo, but the referee ruled otherwise.
However, Alonso had the final say to end the brave bid of South Africa, who also pushed Brazil close in the other semi-final before losing 1-0 to a late Daniel Alves free-kick.