'String + foreach loop together in a variable in php
I'm trying to loop through a json api response. I than need to write this to a table on a page through fopen(); I can loop through the first loop which loops the header of the table but i'm stuck at the second loop where the loop should the table data.
$arr = json_decode($response, true);
$domain = $arr['pricing'];
$header = "<?php include '../includes/header.php'?>";
$footer = "<?php include '../includes/footer.php'?>";
foreach ($domain as $tld => $result) {
$tld_array[] = $tld;
};
foreach ($tld_array as $domain_tld) {
$tld_price = $arr['pricing'][$domain_tld]['register'][1];
$tld_price_transfer = $arr['pricing'][$domain_tld]['transfer'][1];
$tld_price_renewel = $arr['pricing'][$domain_tld]['renew'][1];
$myfile = fopen("domains.php", "w");
$txt = $header . '
<section>
<div class="container">
<h2 class="display-5 text-center mb-4 fw-bold my-5 p-2 p-sm-5">COMPARE PLANS</h2>
<div class="table-responsive">
<table class="table text-start">
<thead>
<tr>
<th>TLD</th>
<th>Registration</th>
<th>Transfer</th>
<th>Renewel</th>
</tr>
</thead>
<tbody>
<tr>
<td>' . $domain_tld . '</td>
<td>' . $tld_price . '</td>
<td>' . $tld_price_transfer . '</td>
<td>' . $tld_price_renewel . '</td>/
<tr>
</tbody>
</table>
</div>
</div>
</section>
' . $footer;
fwrite($myfile, $txt);
fclose($myfile);
}
Solution 1:[1]
Code failed to copy the string contents
[Talking about string here, not the type string]
In C, a string is "... is a contiguous sequence of characters terminated by and including the first null character."
Code only copied pointers and not the string contents.
string key = argv[1];
string keyupper = argv[1];
string keylower = argv[1];
Comment discussion indicates OP now sees why code is in error.
Repaired code
//#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
// Avoid naked magic numbers, instead define them
#define KEY_N 26
int main(int argc, string argv[]) {
// Do not code argv[1] until after argc check
// string key = argv[1];
// string keyupper = argv[1];
// string keylower = argv[1];
if (argc != 2) {
printf("Please input a key.\n");
return 1;
}
char *key = argv[1];
// else if (strlen(key) != 26)letters
if (strlen(key) != KEY_N) {
printf("Please make sure the key is 26 unique letters.\n");
return 1;
}
char keyupper[KEY_N + 1];
char keylower[KEY_N + 1];
// for (int i = 0; i < 26; i++)
for (size_t i = 0; i < KEY_N; i++) {
// keyupper[i] = toupper(keyupper[i]);
keyupper[i] = toupper((unsigned char) key[i]);
}
keyupper[KEY_N] = '\0';
...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
