Liver fibrosis (LF) is a common complication of type 2 diabetes mellitus (T2DM). Studies have found that dietary magnesium (Mg), as an antioxidant nutrient, may be related to the occurrence and development of liver diseases. The aim of the present study was to evaluate the association between dietary Mg and the risk of LF in T2DM patients. In this cross-sectional study, data of T2DM patients, aged ≥18 years, were extracted from the National Health and Nutrition Examination Survey (NHANES 2017-2018). Dietary Mg intake information was obtained by 24-hour dietary recall review. Covariates included sociodemographic information, lifestyle, laboratory data, disease history and medication history, extracted from the database. Weighted univariable and multivariable logistic regression models were used to assess the association between dietary Mg intake and LF among T2DM patients, with odds ratio (OR) and 95% confidence interval (CI). Subgroup analyses based on patients with or without a history of hepatic steatosis were further assessed. A total of 945 participants were finally included, of whom 219 (23.17%) had LF. After adjusting for covariates, a high level of dietary Mg intake (OR=0.40, 95%CI: 0.17-0.93) was associated with lower odds of LF in T2DM patients, especially in patients with a history of hepatic steatosis (OR=0.39, 95%CI: 0.17-0.87). High dietary Mg intake has potential benefits in maintaining a healthy liver in T2DM patients. Sufficient Mg-rich foods and Mg supplementation may be beneficial for liver health management among T2DM patients. Further cohort studies are needed to confirm these findings.