如何去除访问JSON数据时文件路径字段中的正斜杠及相关PHP问题
Solution to Remove Forward Slashes from File Path Fields in JSON Output
Got it, let's fix that forward slash issue in your file path fields when generating JSON from your PHP database query. The key is to modify the path data right after fetching each row from the database, before adding it to your final data array.
Here's the updated PHP code with the fix (I’ll assume your file path column is named file_path—adjust this to match your actual database column name):
<?php $host='localhost'; $username=''; $pwd=''; $db=""; $con=mysqli_connect($host,$username,$pwd,$db) or die('Unable to connect'); if(mysqli_connect_error($con)) { echo "Failed to Connect to Database ".mysqli_connect_error(); } $sql="SELECT * FROM qtb"; $result=mysqli_query($con,$sql); if($result) { $data = []; // Initialize empty array to avoid undefined variable warnings while($row=mysqli_fetch_array($result)) { // Choose one of the options below based on your needs: // Option 1: Remove ALL forward slashes in the file path $row['file_path'] = str_replace('/', '', $row['file_path']); // Option 2: Only remove leading/trailing forward slashes (keep internal ones) // $row['file_path'] = trim($row['file_path'], '/'); $data[] = $row; } // Complete the JSON encoding with your QOB wrapper print(json_encode(array('QOB' => $data))); } else { echo "Query failed: ".mysqli_error($con); } mysqli_close($con); // Clean up database connection ?>
Quick Breakdown:
- Option 1: Use
str_replace('/', '', $row['file_path'])if you want to strip every forward slash from the path entirely. - Option 2: Use
trim($row['file_path'], '/')if you only need to clean up slashes at the start or end of the string (leaving internal slashes intact, which is common for valid file paths). - Don’t forget to replace
file_pathwith the actual column name from yourqtbtable that stores the file paths. - I added small improvements like initializing the
$dataarray and closing the database connection to avoid potential warnings.
If you have multiple path fields to clean, just repeat the str_replace/trim step for each relevant column inside the while loop.
内容的提问来源于stack exchange,提问作者user7091075
相关产品推荐
相关产品推荐

