I am trying to display on an Wordpress webpage certain values contained in a CSV file (which is hosted online) by using PHP. I update this CSV file every X hours via a Python FTP code.
The webpage has the following permalink https://example.com/user/id/
.
The CSV file is hosted on the website and is made up by multiple rows with the same number of columns. Example:
username,user_id,value1,value2,value3,value4
mario,1,1000,1100,1200,1300
luigi,2,2000,2100,2200,2300
...
I would like to parse the CSV file and display values selectively depending on the id
of the user.
I can get the id
of the user from the permalink of the page with the following function:
<?php
$permalink = get_permalink(); // $permalink is now 'https://example.com/user/1/'
$permalink = trim($permalink, "/"); // $permalink is now 'https://example.com/user/1'
$user_id = substr($permalink, strrpos($permalink, '/') + 1); // $user_id is now '1'
?>
Now that I have the user_id
, I would like to show the values in its row. For example, if user_id
is "1" (second column of the CSV file), then I would like to display on the webpage the following output:
Value 1 is 1000
Value 2 is 1100
Value 3 is 1200
Value 4 is 1400
To display the values in the webpage I tried to use something like this:
$csv_url = "https://example.com/path/filename.csv"
$f = file_get_contents($csv_url);
$items = explode(',', $f);
foreach($items as $item){
$user = explode(",", $item);
// $user[0] - will contain the first number
// $user[1] - will contain second
// $user[3] - will contain third
}
But this is not working as intended because it cannot separate the rows.
What PHP code would achieve the result I would like to get?
EDIT New code is:
<?php
$permalink = 'https://example.com/user/1/'; // $permalink is now 'https://example.com/user/1/'
$permalink = trim($permalink, "/"); // $permalink is now 'https://example.com/user/1'
$user_id = substr($permalink, strrpos($permalink, '/') + 1); // $user_id is now '1'
$csv_url = "https://example.com/path/users.csv"
$f = file_get_contents($csv_url);
$lines = explode("\n", $f);
foreach($lines as $line){
$user = explode(",", $line);
if ($user[1] !== $user_id) {
continue;
}
echo "<strong>Points:</strong>"
echo "Value 1: " . $user[2]
echo "Value 2" . $user[3]
echo "Value 3: " . $user[4]
echo "Value 4: " . $user[5]
echo "Value 5: " . $user[6]
}
?>