José de San Martín, who had already helped to liberate Chile and Argentina, entered Peru in 1820. In 1821, the inhabitants of Lima invited him and his soldiers to the city. The viceroy fled into the interior of the country. From there he resisted successfully, and it was only with the arrival of Simón Bolívar and Antonio José de Sucre in 1823 that the Spanish royalist forces were defeated at the battles of Junin and Ayacucho, where the entire Spanish Army of Peru and the Viceroy were captured. The Battle of Ayacucho signified the end of the Spanish Empire on the American mainland.