In order to answer your question, I am going to assume that you are asking about the historical development of Lat. ⟨x⟩ /ks/ > Ibero-Romance /ʃ/, and not about the orthography. As Colin Fine has pointed out in his comment, these are two different issues, but I am going to focus only on the first one, as I feel this is closer to what you want to know.
First of all, the change in question represents the regular development of Lat. x in Ibero-Romance languages. If you find a Portuguese (henceforth Port.) or Spanish (henceforth Sp.) word that contains the sequences /ks/ or /gz/, and they have a clear cognate in Latin, then you are most likely dealing with a learned borrowing.
Having said this, if we want to explain the evolution of Lat. x > /ʃ/ in Ibero-Romance, we should consider that in Latin ⟨x⟩ represents a consonant cluster /ks/. Now, a peculiar sound change happened during the development of Ibero-Romance: I am talking about the yodization of every syllable-final occlusive. In symbols, we have Lat. t /t/, c /k/ > Iber.-Rom. *i̯ /j/. To give you some examples of this change, consider words like Lat. octō > Iber.-Rom. *oi̯to > Sp. ocho, Port. oito 'eight', Lat. auricula > Vulg. Lat. *orecla > Iber.-Rom. *orei̯la > Sp. oreja, Port. orelha 'ear', etc.
As you can see, this yod (by which I mean the *i̯ sound) has the power to palatalize almost any other sound coming before or after it, creating for example Sp. ⟨ch⟩ /ʧ/ and Port. ⟨lh⟩ /ʎ/.
So, what about Lat. x? Well, since this represents a cluster, as we've just said, we should expect a development like Lat. /ks/ > Iber.-Rom. *i̯s /js/, which clearly conforms to what has been discussed above. Then, this sequence *-i̯s- became /ʃ/ through the palatalization triggered by the yod.
A compelling example of this development can be found in Lat. coxā /koksaː/ > Iber.-Rom. *koi̯sa > Port. coxa /koʃa/ 'hip, thigh'. We have two pieces of evidence that allow us to claim that this is the right development. First, the Old Portuguese equivalent of coxa is coixa or coissa (a similar word coyxa exists in Old Galician as well). This confirms that in this word there was an old yod, occasionally written as ⟨i⟩ in Old Portuguese orthography. Secondly, Spanish has cuja 'a kind of bag tied to the hips of a horse', which is derived from the same Latin term. Normally, Latin o > Sp. ue, but in this case it undoubtedly developed into u because the starting point of the derivation was Iber.-Rom. *koi̯sa (with yod), and not *kosa (which would have given Sp. *cuesa). In fact, middle vowels in Ibero-Romance became high vowels in Spanish in the vicinity of a yod. Therefore, we have Iber.-Rom. *koi̯sa > *kui̯sa > *kuʃa > Sp. cuja.
All these elements prove that Lat. x /ks/ changed into *-i̯s- /-js-/ in Ibero-Romance languages. At a later stage, this cluster underwent palatalization, resulting in the expected outcome /ʃ/.
I hope this answers your question.