Spain secured third place at the Confederations Cup when Xabi Alonso curled home a long-range free kick to give them a 3-2 win over hosts South Africa after extra time in Rustenburg.
|Sergi Busquets and Xabi Alonso celebrate Daniel Guiza's second goal [AFP]
Alonso's 107th minute effort evaded both his own strikers and the home defence to settle a thrilling match that produced several twists.
South African substitute Katlego Mphela forced the match into extra time with a ferocious free kick with the last kick at the end of 90 minutes.
Goals in the 88th and 89th minutes from second-half substitute Daniel Guiza had put the European champions 2-1 up heading into stoppage time.
Mphela had given South Africa the lead in the 73rd minute, sending the home crowd into raptures.
He had some difficulty bringing a bouncing ball under control but drilled home a
left-footed shot from almost point blank range.
Guiza, who had come on for Fernando Torres, equalised after collecting a through-ball from Alonso as the South African defence backed off and allowed him to shoot from close in.
The Turkish-based striker then looked to have turned the result in Spain's favour when, within seconds, he floated a the ball over South African goalkeeper Itumeleng Khune.
But Mphela blasted home a free kick from some 25 metres out to add an additional 30 minutes to the tie.
Spain might have had a penalty in extra time when South African defender Benson Mhlongo handled the ball but it was not spotted by the Australia referee.
They also had an effort from Sergio Busquets ruled offside early in the second half although television replays suggested it was a legitimate goal.