I was told to open the gas cap again and close it after driving for a while, which it does work after I open it and close it at least twice and the light goes on, but I don't want this to continue, do I have to buy a new gas cap or it may be something else.
sometimes when I fillup the gas tank, the service engine comes on, on 2004 BMW 330xi
You obviously shouldn't have to open and close the gas cap. What codes are stored? If an evap code ,the computer only tests the evap system under certain criteria (fuel tank fuel level between approx 1/4 and 3/4 full). Gas caps are cheap you could try that. The computer takes a while to recognize that the cap has been replaced and when it does see the fault is gone it will erase the Check Engine Light itself but it may take two weeks of driving or more. If a scan tool is used make sure codes stored are written down and you have a copy of the codes.