The plot draws largely from an English legend, "The Pedlar of Swaffham", which has been also used by Borges in his Tale of Two Dreamers, collected in Universal History of Infamy.
Another possible source is also in the work of the 13th century Persian poet Jalal al-Din Rumi, who in one of the stories of his Mathanawi tells an almost identical tale. In a modern translation the story (told in verse) is titled "In Baghdad, Dreaming of Cairo: In Cairo, Dreaming of Baghdad". In it, a poor man in Baghdad who inherits a lot of money and land only to squander it quickly and become poor again has a dream, in which a voice tells him to go to Cairo and dig in a certain spot to find his wealth. When he gets there, while wandering the streets and begging for coins he is picked up by a night patrol. When he tells his story to the patrolman, the latter calls him a fool and tells him of a similar dream (which he had dismissed) about a place in Baghdad, describing the very street and house in which the poor man lives.
Identify the work.