Reading Line by Line Using PHP Via JSON String - php
I am trying to create a PHP function which will allow me to read selected lines from a text file using a JSON string. The JSON string consists of two numbers separated by a comma. The first number is the line I want to seek, and the second is the number of lines to read going downward.
For example, I have this sentence in a separate text file:
A diving spiral attack in which Pikachu head butts downward while
being surrounded by electricity.
(If you're wondering, this is part of my upcoming fan site, still under construction).
The sentence starts at line 6, and uses up 2 lines. So in my JSON file, I would write "6,2". The explode() command is ran using the comma as the delimiter, allowing me to store these number into two individual variables, $start and $length.
$result = explode(",", $sample); // In JSON string, $sample is $i["desc"]
$start = $result[0];
$length = $result[1];
With the variables now in place, the following lines will then be called to perform the actual line-by-line extraction.
$file = new SplFileObject("pikachu/pikachu.txt");
for ($i = $start; $i <= ($start+$length); $i++) {
$file->seek($i-1);
echo "$file";
}
I did a test of my script using a direct call instead of through JSON parsing. That worked. But when I tried to use the JSON string, I ended up with both a Runtime and a Fatal Error.
How do I fix the scripts so that I can use the JSON string as markers for seeking lines from an external text to print while avoiding the Runtime and Fatal Errors?
(EDIT: The problem became too difficult for me to fix, so I've decided to ditch the line-by-line seek feature for now. I will revisit this on a later date. I will leave the code below for archival purposes.)
character.php
<?php
$name = $_GET['name'];
// Step 1: Get the name from the previous page and store it.
$file = file_get_contents("characters/$name/$name.json");
// Step 2: Use the name to find a JSON file for the character (We'll do the moves list later).
$json = json_decode($file, true);
// Step 3: Decode the JSON file
$character = $json["character"][0]["name"];
$group = $json["character"][0]["group"];
$series = $json["character"][0]["series"];
$story = $json["character"][0]["story"];
$snapback = $json["character"][0]["snapback"];
$interrupt = $json["character"][0]["interrupt"];
$hiddenpow = $json["character"][0]["hiddenpow"];
$disrupt = $json["character"][0]["disrupt"];
$assist1 = $json["character"][0]["assist1"];
$assist2 = $json["character"][0]["assist2"];
$assist3 = $json["character"][0]["assist3"];
$counter = $json["character"][0]["counter"];
$bros = $json["character"][0]["bros"];
$party = $json["character"][0]["party"];
$ground = $json["character"][0]["ground"];
$jump = $json["character"][0]["jump"];
$superjump = $json["character"][0]["superjump"];
$launcher = $json["character"][0]["launcher"];
$altlaunch = $json["character"][0]["altlaunch"];
$acfinisher = $json["character"][0]["acfinisher"];
// Step 4: Retrieve variables and store them for use
echo "<HTML>\n";
echo "<HEAD>\n";
echo "<TITLE>Marvel & Capcom vs. Pokemon: $character</TITLE>\n\n";
echo "<LINK rel=\"stylesheet\" type=\"text/css\" href=\"http://fonts.googleapis.com/css?family=Roboto\">\n";
echo "<LINK rel=\"stylesheet\" type=\"text/css\" href=\"http://fonts.googleapis.com/css?family=Open+Sans\">\n";
echo "<LINK rel=\"stylesheet\" type=\"text/css\" href=\"media/style.css\">\n";
echo "<SCRIPT type=\"text/javascript\" src=\"media/tabs.js\"></SCRIPT>\n";
echo "<SCRIPT type=\"text/javascript\">\n";
echo "function toggle_visibility(id) {\n";
echo " var movename = id.nextSibling.nextSibling;\n";
echo " if(movename.style.display == \"block\")\n";
echo " movename.style.display = \"none\";\n";
echo " else\n";
echo " movename.style.display = \"block\";\n";
echo "}\n";
echo "</SCRIPT>";
echo "</HEAD>\n\n";
echo "<BODY onload=\"init()\">\n\n";
// Step 5: The HTML stuff begins
echo "<TABLE id=\"Character\">\n";
echo " <TR>\n";
echo " <TD class=\"Name\">" . strtoupper($character) . "</TD>\n";
echo " <TD class=\"Image\" rowspan=\"4\"><IMG src=\"characters/$name/$name.jpg\"></TD></TR>\n";
echo " <TR>\n";
echo " <TD class=\"Series\">Series: $series</TD></TR>\n";
echo " <TR>\n";
echo " <TD class=\"Story\">$story</TD></TR>\n";
// Step 6: Write the variables to the file
echo " <TR>\n";
echo " <TD style=\"vertical-align: top\">\n";
echo " <TABLE id=\"$group\">\n";
function moverw ($move) {
$subfollow = "FOLLOW>>";
$follow = "FOLLOW>";
if (strpos($move,$subfollow) !== false)
$move .= " (followup)";
else if (strpos($move,$follow) !== false)
$move .= " (followup)";
$move = str_replace("FOLLOW>>", "<IMG class=\"Followup\" src=\"images/follow.png\" style=\"text-indent: 5px\"> ", $move);
$move = str_replace("FOLLOW>", "<IMG class=\"Followup\" src=\"images/follow.png\"> ", $move);
return ($move);
}
function descrw ($desc,$name) {
$result = explode(",", $desc);
$start = $result[0];
$length = $result[1];
$file = new SplFileObject("characters/$name/$name.txt");
$result = "";
for ($i = $start; $i <= ($start+$length); $i++) {
$file->seek($i-1);
$result .= $file;
}
return($result);
}
function commrw ($command) {
$command = str_replace("AM,", "<IMG title=\"Assist Mode\" src=\"images/assist.gif\"> ", $command);
$command = str_replace("SM,", "<IMG title=\"Single Mode\" src=\"images/single.gif\"> ", $command);
$command = str_replace("BRAWL,", "<IMG title=\"Super Smash Brawl\" src=\"images/brawl.png\"> ", $command);
$command = str_replace("uf,", "<IMG class=\"Arrow\" src=\"images/uf.png\">", $command);
$command = str_replace("df,", "<IMG class=\"Arrow\" src=\"images/df.png\">", $command);
$command = str_replace("ub,", "<IMG class=\"Arrow\" src=\"images/ub.png\">", $command);
$command = str_replace("db,", "<IMG class=\"Arrow\" src=\"images/db.png\">", $command);
$command = str_replace("u,", "<IMG class=\"Arrow\" src=\"images/u.png\">", $command);
$command = str_replace("f,", "<IMG class=\"Arrow\" src=\"images/f.png\">", $command);
$command = str_replace("d,", "<IMG class=\"Arrow\" src=\"images/d.png\">", $command);
$command = str_replace("b,", "<IMG class=\"Arrow\" src=\"images/b.png\">", $command);
$command = str_replace("+", "<IMG class=\"Plus\" src=\"images/plus.png\">", $command);
$command = str_replace("AP", "<IMG class=\"Button\" src=\"images/punch.png\">", $command);
$command = str_replace("AK", "<IMG class=\"Button\" src=\"images/kick.png\">", $command);
$command = str_replace("A1", "<IMG class=\"Button\" title=\"Assist 1\" src=\"images/assist1.png\">", $command);
$command = str_replace("A2", "<IMG class=\"Button\" title=\"Assist 2\" src=\"images/assist2.png\">", $command);
$command = str_replace("AB", "<IMG class=\"Button\" title=\"Assist\" src=\"images/assist.png\">", $command);
$command = str_replace("LP", "<IMG class=\"Button\" title=\"Jab\" src=\"images/jab.png\">", $command);
$command = str_replace("LK", "<IMG class=\"Button\" title=\"Short\" src=\"images/short.png\">", $command);
$command = str_replace("MP", "<IMG class=\"Button\" title=\"Strong\" src=\"images/strong.png\">", $command);
$command = str_replace("MK", "<IMG class=\"Button\" title=\"Forward\" src=\"images/forward.png\">", $command);
$command = str_replace("HP", "<IMG class=\"Button\" title=\"Fierce\" src=\"images/fierce.png\">", $command);
$command = str_replace("HK", "<IMG class=\"Button\" title=\"Roundhouse\" src=\"images/roundhouse.png\">", $command);
$command = str_replace("FOLLOW>>", "<IMG class=\"Followup\" src=\"images/follow.png\" style=\"text-indent: 5px\"> ", $command);
$command = str_replace("FOLLOW>", "<IMG class=\"Followup\" src=\"images/follow.png\"> ", $command);
$command = str_replace("degrees", "°", $command);
return ($command);
}
function typerw ($type) {
$type = str_replace("BUG.", "<IMG src=\"images/bug.png\">", $type);
$type = str_replace("CYBER.", "<IMG src=\"images/cyber.png\">", $type);
$type = str_replace("DARK.", "<IMG src=\"images/dark.png\">", $type);
$type = str_replace("DRAGON.", "<IMG src=\"images/dragon.png\">", $type);
$type = str_replace("ELECTRIC.", "<IMG src=\"images/electric.png\">", $type);
$type = str_replace("FAIRY.", "<IMG src=\"images/fairy.png\">", $type);
$type = str_replace("FIGHTING.", "<IMG src=\"images/fighting.png\">", $type);
$type = str_replace("FIRE.", "<IMG src=\"images/fire.png\">", $type);
$type = str_replace("FLYING.", "<IMG src=\"images/flying.png\">", $type);
$type = str_replace("GHOST.", "<IMG src=\"images/ghost.png\">", $type);
$type = str_replace("GRASS.", "<IMG src=\"images/grass.png\">", $type);
$type = str_replace("GROUND.", "<IMG src=\"images/ground.png\">", $type);
$type = str_replace("ICE.", "<IMG src=\"images/ice.png\">", $type);
$type = str_replace("LIGHT.", "<IMG src=\"images/light.png\">", $type);
$type = str_replace("NORMAL.", "<IMG src=\"images/normal.png\">", $type);
$type = str_replace("PSYCHIC.", "<IMG src=\"images/psychic.png\">", $type);
$type = str_replace("STEEL.", "<IMG src=\"images/steel.png\">", $type);
$type = str_replace("WATER.", "<IMG src=\"images/water.png\">", $type);
return ($type);
}
function noterw ($note) {
$note = str_replace(".AM.", "<IMG title=\"Assist Mode\" src=\"images/assist.gif\"> ", $note);
$note = str_replace(".SM.", "<IMG title=\"Single Mode\" src=\"images/single.gif\"> ", $note);
$note = str_replace(".HP.", "<IMG class=\"HiddenPower\" title=\"Hidden Power\"src=\"images/hiddenpower.png\">", $note);
return ($note);
}
foreach ($json["character"][0]["moves"] as $i) {
if ($i["flag"] == "normal") {
$move = strtoupper($i["move"]);
$desc = $i["desc"];
$command = $i["comm"];
$type = $i["type"];
$note = $i["note"];
echo " <TR>\n";
echo " <TD class=\"MoveName Normal\">" . moverw($move) . "\n";
echo " <DIV class=\"Details\">" . descrw($desc,$name) . "</DIV></TD>\n";
echo " <TD class=\"Command\">" . commrw($command) . "</TD>\n";
echo " <TD class=\"Type\">" . typerw($type) . "</TD>\n";
echo " <TD class=\"Note\">" . noterw($note) . "</TD></TR>\n";
}
if ($i["flag"] == "special") {
$move = strtoupper($i["move"]);
$command = $i["comm"];
$type = $i["type"];
$note = $i["note"];
echo " <TR>\n";
echo " <TD class=\"MoveName Special\">" . moverw($move) . "\n";
echo " <DIV class=\"Details\">" . $i["desc"] . "</DIV></TD>\n";
echo " <TD class=\"Command\">" . commrw($command) . "</TD>\n";
echo " <TD class=\"Type\">" . typerw($type) . "</TD>\n";
echo " <TD class=\"Note\">" . noterw($note) . "</TD></TR>\n";
}
if ($i["flag"] == "hyper") {
$move = strtoupper($i["move"]);
$command = $i["comm"];
$type = $i["type"];
$note = $i["note"];
echo " <TR>\n";
echo " <TD class=\"MoveName Hyper\">" . moverw($move) . "\n";
echo " <DIV class=\"Details\">" . $i["desc"] . "</DIV></TD>\n";
echo " <TD class=\"Command\">" . commrw($command) . "</TD>\n";
echo " <TD class=\"Type\">" . typerw($type) . "</TD>\n";
echo " <TD class=\"Note\">" . noterw($note) . "</TD></TR>\n";
}
if ($i["flag"] == "final") {
$move = strtoupper($i["move"]);
$command = $i["comm"];
$type = $i["type"];
$note = $i["note"];
echo " <TR>\n";
echo " <TD class=\"MoveName Final\">" . moverw($move) . "\n";
echo " <DIV id=\"Final\" class=\"Details\">" . $i["desc"] . "</DIV></TD>\n";
echo " <TD class=\"Command\">" . commrw($command) . "</TD>\n";
echo " <TD class=\"Type\">" . typerw($type) . "</TD>\n";
echo " <TD class=\"Note\">" . noterw($note) . "</TD></TR>\n";
}
}
// Step 7: Write the moves. When Command and Type are parsed, execute respective rewriters. Saves me from typing lots, hun ;)
echo " </TABLE></TD></TR>\n";
echo " <TR>\n";
echo " <TD colspan=\"2\">\n";
echo " <UL id=\"tabs\">\n";
echo " <LI>SINGLE MODE</LI>\n";
echo " <LI>ASSIST MODE</LI>\n";
echo " <LI>COMBO PROFILE</LI>\n";
echo " <LI>ATTACK PROFILE</LI></UL>\n";
echo " <DIV class=\"tabContent\" id=\"Single\">\n";
echo " <TABLE id=\"Single\" border=1>\n";
echo " <TR>\n";
echo " <TH>Snapback:</TH>\n";
echo " <TD>$snapback</TD></TR>\n";
echo " <TR>\n";
echo " <TH>Interrupt:</TH>\n";
echo " <TD>$interrupt</TD></TR>\n";
echo " <TR>\n";
echo " <TH>Hidden Power:</TH>\n";
echo " <TD>$hiddenpow</TD></TR>\n";
echo " <TR>\n";
echo " <TH class=\"Header Rumble\"colspan=\"2\">RUMBLE CHART</TH></TR>\n";
echo " <TR>\n";
echo " <TD colspan=\"2\"></TH></TR></TABLE></DIV>\n";
echo " <DIV class=\"tabContent\" id=\"Assist\">\n";
echo " <TABLE id=\"Assist\" border=1>\n";
echo " <TR>\n";
echo " <TH>Disrupt:</TH>\n";
echo " <TD>$disrupt</TD></TR>\n";
echo " <TR>\n";
echo " <TH colspan=2>Assist Attacks</TH></TR>\n";
echo " <TR>\n";
echo " <TH><IMG class=\"Button\" title=\"Assist\" src=\"images/assist.png\"></TH>\n";
echo " <TD>$assist1</TD></TR>\n";
echo " <TR>\n";
echo " <TH><IMG class=\"Button\" title=\"Assist\" src=\"images/assist.png\"><IMG class=\"Plus\" src=\"images/plus.png\"><IMG class=\"Button\" title=\"Fierce\" src=\"images/fierce.png\"></TH>\n";
echo " <TD>$assist2</TD></TR>\n";
echo " <TR>\n";
echo " <TH><IMG class=\"Button\" title=\"Assist\" src=\"images/assist.png\"><IMG class=\"Plus\" src=\"images/plus.png\"><IMG class=\"Button\" title=\"Roundhouse\" src=\"images/roundhouse.png\"></TH>\n";
echo " <TD>$assist3</TD></TR>\n";
echo " <TR>\n";
echo " <TH>Cross-Over Counter:</TH>\n";
echo " <TD>$counter</TD></TR>\n";
echo " <TR>\n";
echo " <TH colspan=2>Super Smash Melee</TH></TR>\n";
echo " <TR>\n";
echo " <TH>Bros. Attack:</TH>\n";
echo " <TD>$bros</TD></TR>\n";
echo " <TR>\n";
echo " <TH>Party Attack:</TH>\n";
echo " <TD>$party</TD></TR></TABLE></DIV>\n";
echo " <DIV class=\"tabContent\" id=\"Combo\">\n";
echo " <TABLE id=\"Combo\" border=1>\n";
echo " <TR>\n";
echo " <TH colspan=2>???</TH></TR>\n";
echo " <TR>\n";
echo " <TH>Ground:</TH>\n";
echo " <TD>$ground</TD></TR>\n";
echo " <TR>\n";
echo " <TH>Jump:</TH>\n";
echo " <TD>$jump</TD></TR>\n";
echo " <TR>\n";
echo " <TH>Super Jump:</TH>\n";
echo " <TD>$superjump</TD></TR>\n";
echo " <TR>\n";
echo " <TH colspan=2></TH></TR>\n";
echo " <TR>\n";
echo " <TH>Launcher:</TH>\n";
echo " <TD>$launcher</TD></TR>\n";
if ($altlaunch != null) {
echo " <TR>\n";
echo " <TH>Alternate Launch:</TH>\n";
echo " <TD>$altlaunch</TD></TR>\n";
}
echo " <TR>\n";
echo " <TH>AC Finishers:</TH>\n";
echo " <TD>$acfinisher</TD></TR></TABLE></DIV>\n";
echo " <DIV class=\"tabContent\" id=\"Attack\">\n";
echo " $test 4\n";
echo " </DIV>\n";
echo " </TD></TR></TABLE></TD></TR></TABLE>\n\n";
echo "</BODY></HTML>";
?>
$name.json, where $name is the name of the character (using pikachu as demo):
{"character":[
{
"name":"Pikachu",
"group":"Pokemon",
"series":"Pokemon",
"story":"To-do...",
"moves":[
{
"flag":"normal",
"move":"Discharge",
"desc":"3,2",
"comm":"Press HP (crouch) (air)",
"type":"ELECTRIC.",
"note":"Notes"
},
{
"flag":"normal",
"move":"Electric Screw",
"desc":"6,2",
"comm":"Tilt d,+HP [air]",
"type":"ELECTRIC.",
"note":"Notes"
},
{
"flag":"normal",
"move":"Tackle",
"desc":"9,1",
"comm":"Tap f, , f,",
"type":"NORMAL.",
"note":"Notes"
},
{
"flag":"special",
"move":"Quick Attack",
"desc":"11,2",
"comm":"Tap any direction and Press AP (air)",
"type":"ELECTRIC.FIGHTING.",
"note":"Notes"
},
{
"flag":"special",
"move":"Thunder Jolt",
"desc":"14",
"comm":"Motion d,df,f,+AP",
"type":"ELECTRIC.",
"note":"Notes"
},
{
"flag":"special",
"move":"Electro Ball",
"desc":"16,2",
"comm":"Motion d,df,f,+AP [air]",
"type":"ELECTRIC.",
"note":"Notes"
},
{
"flag":"special",
"move":"Thunder",
"desc":"19,2",
"comm":"Motion f,d,df,+AP (air)",
"type":"ELECTRIC.",
"note":"Notes"
},
{
"flag":"special",
"move":"Electric Chair",
"desc":"22,2",
"comm":"Motion f,df,d,db,b,+AP",
"type":"ELECTRIC.",
"note":"Notes"
},
{
"flag":"hyper",
"move":"Thunder Shock",
"desc":"25,2",
"comm":"Motion d,df,f,+APAP (air)",
"type":"ELECTRIC.",
"note":"Notes"
},
{
"flag":"hyper",
"move":"Thunder Bolt",
"desc":"28,1",
"comm":"Motion d,df,f,+AKAK (air)",
"type":"ELECTRIC.",
"note":"Notes"
},
{
"flag":"hyper",
"move":"Skull Bash",
"desc":"30,2",
"comm":"Motion d,db,b,+APAP (air)",
"type":"ELECTRIC.FIGHTING.",
"note":"Notes"
},
{
"flag":"final",
"move":"Volt Tackle",
"desc":"33,2",
"comm":"Motion d,df,f,d,df,f,+APAP (air)",
"type":"ELECTRIC.",
"note":"Notes"
}],
"snapback":"Crouching Forward",
"interrupt":"Thunder Jolt, Thunder",
"hiddenpow":"Hidden Power Enhancements (Line per line lookup)",
"disrupt":"Thunder",
"assist1":"Thunder Jolt",
"assist2":"Thunder",
"assist3":"Quick Attack",
"counter":"Thunder",
"bros":"Skull Bash",
"party":"Thunder Bolt",
"ground":"Punch to Kick",
"jump":"Punch to Kick",
"superjump":"Zig Zag",
"launcher":"Standing Roundhouse",
"altlaunch":"Crouching Strong",
"acfinisher":"Discharge, Electric Screw, Quick Attack, Electro Ball, Thunder, Thunder Shock, Thunder Bolt, Skull Bash"
}
]}
The problem is in this function, and has nothing to do with your use of JSON. It's just a simple variable scope issue.
function descrw ($desc) {
$result = explode(",", $desc);
$start = $result[0];
$length = $result[1];
$file = new SplFileObject("$name/$name.txt");
for ($i = $start; $i <= ($start+$length); $i++) {
$file->seek($i-1);
echo "$file";
}
return(0);
}
The variable $name is not defined, so it's trying to open the file /.txt. You need to change the function so it takes $name as an argument. And since the caller of descrw expects it to return a string so that it can be concatenated, descrw shouldn't do its own echo.
function descrw ($desc, $name) {
$result = explode(",", $desc);
$start = $result[0];
$length = $result[1];
$file = new SplFileObject("$name/$name.txt");
$result = '';
for ($i = $start; $i <= ($start+$length); $i++) {
$file->seek($i-1);
$result .= $file;
}
return($result);
}
Then change the place where it's called to pass the argument:
echo " <DIV class=\"Details\">" . descrw($desc, $name) . "</DIV></TD>\n";
Related
Illegal String Offset in Multidimensional Array
I am attempting to fetch a JSON file from a separate website, read that file and then decode it into a multidimensional array. So far at that point it seems to work. However, when I try and break it all down into variables to echo, it goes wrong when its 4 levels deep. You can see the actual JSON file from the link in the PHP code and below is the PHP Code I am using. The specific variables that have problems are $prices in 2 areas and $rulings. Any help someone can provide with this would be appreciated. <?php $path = 'https://www.mtgjson.com/json/LEA.json'; $FileContents = file_get_contents($path); $cards = json_decode($FileContents, true); foreach ($cards['cards'] as $mtgcard){ $Artist = $mtgcard['artist']; $borderColor = $mtgcard['borderColor']; $colorIdentity = $mtgcard['colorIdentity'][0]; $Colors = $mtgcard['colors'][0]; $convertedManaCost = $mtgcard['convertedManaCost']; $edhrecRank = $mtgcard['edhrecRank']; $flavorText = $mtgcard['flavorText']; $cards_foreignData = implode($mtgcard['foreignData'],","); $foreignData = explode(',', $cards_foreignData); $frameVersion = $mtgcard['frameVersion']; $hasFoil = $mtgcard['hasFoil']; $hasNonFoil = $mtgcard['hasNonFoil']; $isPaper = $mtgcard['isPaper']; $Layout = $mtgcard['layout']; $cards_legalities = implode($mtgcard['legalities'],","); $legalities = explode(',', $cards_legalities); $manaCost = $mtgcard['manaCost']; $mcmId = $mtgcard['mcmId']; $mcmMetaId = $mtgcard['mcmMetaId']; $mtgstocksId = $mtgcard['mtgstocksId']; $multiverseId = $mtgcard['multiverseId']; $name = $mtgcard['name']; $number = $mtgcard['number']; $originalText = $mtgcard['originalText']; $originalType = $mtgcard['originalType']; $power = $mtgcard['power']; $cards_prices = implode($mtgcard['prices'],","); $prices = explode(',', $cards_prices); $cards_prices_2 = implode($cards_prices['paper'],","); $prices_2 = explode(',', $cards_prices_2); $cards_printings = implode($mtgcard['printings'],","); $printings = explode(',', $cards_printings); $cards_purchaseUrls = implode($mtgcard['purchaseUrls'],","); $purchaseUrls = explode(',', $cards_purchaseUrls); $rarity = $mtgcard['rarity']; $cards_rulings = implode($mtgcard['rulings'],","); $rulings = explode(',', $cards_rulings); $scryfallId = $mtgcard['scryfallId']; $scryfallIllustrationId = $mtgcard['scryfallIllustrationId']; $scryfallOracleId = $mtgcard['scryfallOracleId']; $cards_subtypes = implode($mtgcard['subtypes'],","); $subtypes = explode(',', $cards_subtypes); $cards_supertypes = implode($mtgcard['supertypes'],","); $supertypes = explode(',', $cards_supertypes); $tcgplayerProductId = $mtgcard['tcgplayerProductId']; $text = $mtgcard['text']; $toughness = $mtgcard['toughness']; $type = $mtgcard['type']; $types = $mtgcard['types'][0]; $uuid = $mtgcard['uuid']; $a = substr($scryfallId, 0, 1); $b = substr($scryfallId, 1, 1); $convert = "<img src='https://img.scryfall.com/cards/large/front/" .$a. "/" .$b. "/" .$scryfallId. ".jpg' />"; echo $convert; echo "Artist Name: " .$Artist. "<br/>"; echo "Border Color: " .$borderColor. "<br/>"; echo "colorIdentity: " .$colorIdentity. "<br/>"; echo "Colors: " .$Colors. "<br/>"; echo "convertedManaCost: " .$convertedManaCost. "<br/>"; echo "edhrecRank: " .$edhrecRank. "<br/>"; echo "flavorText: " .$flavorText. "<br/>"; echo "foreignData: " .$foreignData[0]. "<br/>"; echo "frameVersion: " .$frameVersion. "<br/>"; echo "hasFoil: " .$hasFoil. "<br/>"; echo "hasNonFoil: " .$hasNonFoil. "<br/>"; echo "isPaper: " .$isPaper. "<br/>"; echo "Layout: " .$Layout. "<br/>"; echo "Brawl: " .$legalities[0]. "<br/>"; echo "Commander: " .$legalities[1]. "<br/>"; echo "Duel: " .$legalities[2]. "<br/>"; echo "Future: " .$legalities[3]. "<br/>"; echo "Historic: " .$legalities[4]. "<br/>"; echo "Legacy: " .$legalities[5]. "<br/>"; echo "Modern: " .$legalities[6]. "<br/>"; echo "Oldschool: " .$legalities[7]. "<br/>"; echo "Penny: " .$legalities[8]. "<br/>"; echo "Pioneer: " .$legalities[9]. "<br/>"; echo "Standard: " .$legalities[10]. "<br/>"; echo "Vintage: " .$legalities[11]. "<br/>"; echo "Manacost: " .$manaCost. "<br/>"; echo "mcmId: " .$mcmId. "<br/>"; echo "mcmMetaId: " .$mcmMetaId. "<br/>"; echo "mtgstocksId: " .$mtgstocksId. "<br/>"; echo "multiverseId: " .$multiverseId. "<br/>"; echo "name: " .$name. "<br/>"; echo "number: " .$number. "<br/>"; echo "originaltext: " .$originalText. "<br/>"; echo "originaltype: " .$originalType. "<br/>"; echo "power: " .$power. "<br/>"; echo "MTGO prices: " .$prices[0]. "<br/>"; echo "MTGO Foil Prices: " .$prices[1]. "<br/>"; echo "Paper Prices: " .prices[2] "<br/>"; <- 4 levels deep doesnt work echo "Paper Foil Prices: " .$prices[3]. "<br/>"; <- 4 levels deep doesnt work echo "purchaseUrls: " .$purchaseUrls[0]. "<br/>"; echo "purchaseUrls: " .$purchaseUrls[1]. "<br/>"; echo "purchaseUrls: " .$purchaseUrls[2]. "<br/>"; echo "rarity: " .$rarity. "<br/>"; echo "ruling: " .$rulings['date'].$rulings['text'] "<br/>"; <-- 4 levels deep doesnt work echo "scryfallId: " .$scryfallId. "<br/>"; echo "scryfallIllustrationId: " .$scryfallIllustrationId. "<br/>"; echo "scryfallOracleId: " .$scryfallOracleId. "<br/>"; echo "subtypes: " .$subtypes[0]. "<br/>"; echo "supertypes: " .$supertypes[0]. "<br/>"; echo "tcgplayerProductId: " .$tcgplayerProductId. "<br/>"; echo "text: " .$text. "<br/>"; echo "toughness: " .$toughness. "<br/>"; echo "type: " .$type. "<br/>"; echo "types: " .$types. "<br/>"; echo "uuid: " .$uuid. "<br/>"; } ?>
You should mention the array name to fetch the content inside array, here is the example code and artist is with small "a" not capital Edit as per comment request Get the array of 'legalities' a string with , separated using implode and than explode with , and convert into an array to print those Note: only the values will be imported using implode not the keys <?php // error_reporting(0); // header('Content-type: application/json'); $path = 'https://www.mtgjson.com/json/LEA.json'; $FileContents = file_get_contents($path); $cards = json_decode($FileContents, true); foreach($cards['cards'] as $mtgcard) { echo '<br>' .$course_data1 = $mtgcard['artist']; $cards_legalities = implode($mtgcard['legalities'],","); $myArray = explode(',', $cards_legalities); echo $myArray[0];// 1st array //Multidimensional Array for your updated question $cards_prices_paper = implode($mtgcard['prices']['paper'],","); $prices_paper_array = explode(',', $cards_prices_paper); echo $prices_paper_array[0]; $rulings_date = implode(', ', array_column($mtgcard['rulings'], 'date')); $rulings_date_array = explode(",", $rulings_date); echo $rulings_date_array[0]; } ?>
How to search defined class or variable's location
These errors keep coming after changing the PHP website to new server. 1st - Solved by "shaddy" Notice: Undefined variable: es in /home/musthand/public_html/external/site/header.php on line 2 <?php if(!is_object($es)) { require_once('includes/EliteScript.php'); $es = new EliteScript(); $sMemberId = $es->getMemberId(); } // Get the base URL $sBaseUrl = $es->getConfig('baseUrl'); $sImageUrl = $es->getConfig('imageUrl'); $sMemberId = $es->getMemberId(); $sUsername = $es->getMemberUsername($sMemberId); $sIP = $_SERVER['REMOTE_ADDR']; // Vars we want to pass to the system $aJSVars = array( 'member_url' => $es->getConfig('memberUrl'), 'base_url' => $es->getCOnfig('baseUrl'), 'image_url' => $es->getConfig('imageUrl'), 'date' => date("F d, Y H:i:s", time()), ); $ba = new BannerAd(); ?> 2nd Fatal error: Class 'FOrum' not found in /home/musthand/public_html/interface/forum.php on line 33 <?php global $es; global $ui; global $member_id; global $base_url; global $member_url; global $image_url; global $admin_url; require_once("includes/EliteScript.php"); $es = new EliteScript(); $ui = new UserInterface(); $es->RequireMember(); $member_id = $es->GetMemberId(); $base_url = $es->GetConfig("baseUrl"); $member_url = $es->GetConfig("memberUrl"); $image_url = $es->GetConfig("imageUrl"); $es->DisplayHeader("Forum", "member.php"); $_REQUEST["do"]; display_main(); $es->DisplayFooter(); function display_main() { global $es; global $ui; global $member_id; global $base_url; global $member_url; global $image_url; global $admin_url; $cur_sign = $es->GetCurrencySign(); $f = new FOrum(); echo "<script>\n</script>\n\n<div class=\"bigHeader\">Forum</div>\n"; echo $ui->GenerateMessageBox("msg", 0, 5); echo $ui->GenerateErrorBox("err", 0, 5); echo "\n"; echo $ui->DisplayToolTip("Forum", "Below you can participate in the company forum."); echo "<br>\n\n\n"; $q = "SELECT * FROM forumSections ORDER BY id"; $r = mysql_query($q); while( $l = mysql_fetch_array($r) ) { $l_sid = $l["id"]; $l_sec_name = htmlentitiesi($l["name"]); echo "<div class=\"header\">"; echo $l_sec_name; echo "</div>\n<table cellspacing=\"1\" cellpadding=\"0\" border=\"0\" width=\"100%\" class=\"dataTbl\">\n<tr class=\"tblHeader\">\n<td>Forum</td>\n<td width=\"50\" align=\"center\">Topics</td>\n<td width=\"50\" align=\"center\">Replies</td>\n<td width=\"150\" align=\"right\">Last Post Info</td>\n</tr>\n"; $html = NULL; $qb = "SELECT * FROM forums WHERE sectionId='" . $l_sid . "' ORDER BY id"; $rb = mysql_query($qb); while( $lb = mysql_fetch_array($rb) ) { $l_fid = $lb["id"]; $l_name = htmlentitiesi($lb["name"]); $l_desc = htmlentitiesi($lb["description"]); $l_topics = $f->GetForumTopicCount($l_fid); $l_replies = $f->GetForumReplyCount($l_fid); $html .= "<tr class=\"tblRowA\">\n\t\t\t<td style=\"padding: 5px 0px 5px 5px;\">\n\t\t\t<b>" . $l_name . "</b>\n\t\t\t<div style=\"padding-top: 5px;\">\n\t\t\t" . $l_desc . "\n\t\t\t</div>\n\t\t\t\n\t\t\t</td>\n\t\t\t<td align=\"center\">" . $l_topics . "</td>\n\t\t\t<td align=\"center\">" . $l_replies . "</td>\n\t\t\t<td align=\"right\">" . $l_lastpost . "</td>\n\t\t\t</tr>"; } echo $html; echo "</table>\n\n"; } echo "\n\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n\n\n\n\n\n<div class=\"header\">News & Updates</div>\n<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\" width=\"100%\">\n"; $html = NULL; $q = "SELECT * FROM news ORDER BY added DESC,id DESC LIMIT 5"; $r = mysql_query($q); while( $l = mysql_fetch_array($r) ) { $l_id = $l["id"]; $l_title = htmlentitiesi($l["title"]); $l_date = date("M jS", strtotime($l["added"])); $html .= "<tr class=\"sepLine\"><td width=\"20\"><img src=\"" . $image_url . "/note.png\" width=\"16\" height=\"16\"></td><td>" . $l_title . " <i style=\"color:gray;\">(" . $l_date . ")</i></td></tr>\n"; } if( !$html ) { $html = "<tr class=\"sepLine\"><td style=\"color: gray;\">Currently no news and updates...</td></tr>"; } echo $html; echo "</table>\n<br>\n\n<div class=\"header\">Account Summary</div>\n\n<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\" width=\"100%\">\n<tr class=\"sepLine\">\n<td width=\"20\"><img src=\""; echo $image_url; echo "/user.png\" width=\"16\" height=\"16\"></td>\n<td width=\"175\"><b>Member Info:</b></td>\n<td>"; echo $username; echo " (#"; echo $member_id; echo ") <i>(<a href=\"mailto:"; echo $email; echo "\">"; echo $email; echo "</a>)</i></td>\n<td align=\"right\"><a href=\""; echo $member_url; echo "/preferences.php\">[Preferences]</a></td>\n</tr>\n</table>\n\n<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\" width=\"100%\">\n<tr><td class=\"toolTip\">\nYou must "; echo $req_text; echo " before participating.</td></tr>\n</table>\n\n\n\n\n<div class=\"header\">Current Active "; echo $token_label; echo "s</div>\n\n<table cellspacing=\"1\" cellpadding=\"0\" border=\"0\" width=\"100%\" class=\"dataTbl\">\n<tr class=\"tblHeader\">\n<td width=\"50\">ID</td>\n<td>Type</td>\n<td width=\"40\">Units</td>\n<td width=\"80\">Amount</td>\n<td width=\"150\">Earned So Far</td>\n<td width=\"80\">Created</td>\n</tr>\n\n"; $tok_types = $es->GetConfig("tokenTypes"); $html = NULL; $tblClass = "tblRowA"; $q = "SELECT * FROM tokens WHERE memberId='" . $member_id . "' AND status = 'ACTIVE' ORDER BY created DESC,id DESC"; $r = mysql_query($q); while( $l = mysql_fetch_array($r) ) { $l_id = $l["id"]; $l_type = $l["type"]; $tok_arr = $tok_types[$l_type]; $l_name = htmlentitiesi($tok_arr["name"]); $l_amt = $l["amount"]; $l_esf = $l["earnedSoFar"]; $l_exp_type = $l["expireType"]; $l_exp_val = $l["expiresOnValue"]; $l_created = $l["createdDate"]; $l_lastroi = $l["lastRoiDate"]; $l_incycle = $l["inCycle"]; $l_status = $l["status"]; if( $l_status == "ACTIVE" ) { $lb_status = "<span style=\"color: darkgreen;\">Active</span>"; } else { if( $l_status == "EXPIRED" ) { $lb_status = "<span style=\"color: red;\">Expired</span> as of " . date("M jS, y", strtotime($l["expiresDate"])); } } if( $l_created == $l_lastroi && $l_incycle <= 1 ) { $l_lastearn_text = "Never"; } else { $l_lastearn_text = date("M jS, y", strtotime($l_lastroi)); } $l_units = sprintf("%d", $l["units"]); $l_earned_per = sprintf("%.2f", $l_esf / $l_amt * 100); $earned_per_style = "color: gray;"; if( 100 < $l_earned_per ) { $earned_per_style = "color: darkgreen;"; } $l_created_date = date("M jS, y", $l["created"]); if( $l_exp_type == "value" ) { $l_exp_text = sprintf("%.2f", $l_exp_val) . "%"; $l_exp_text .= " <i>(" . $cur_sign . sprintf("%.2f", $l_amt * $l_exp_val / 100) . ")</i>"; } else { if( $l_exp_type == "date" ) { $l_exp_text = date("M jS, y", $l["expires"]); } else { if( $l_exp_type == "never" ) { $l_exp_text = "No Set Expiry"; } } } $lb_amt = number_format($l_amt, 2); $lb_esf = number_format($l_esf, 2); $html .= "\n\t\t<tr class=\"" . $tblClass . "\">\n\t\t<td>#" . $l_id . "</td>\n\t\t<td><b>" . $l_name . "</b></td>\n\t\t\n\t\t<td>" . $l_units . "</td>\n\t\t<td>" . $cur_sign . $lb_amt . "</td>\n\t\t<td>" . $cur_sign . $lb_esf . " <i style=\"" . $earned_per_style . "\">(" . $l_earned_per . "%)</i></td>\n\t\t<td>" . $l_created_date . "</td>\n\t\t</tr>\n\t\t<tr class=\"" . $tblClass . "\">\n\t\t<td colspan=\"6\" style=\"padding-left: 20px;\">\n\t\t\n\t\t<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\">\n\t\t<tr><td width=\"170\">\n\t\t<u>Last Earn Date:</u> " . $l_lastearn_text . "\n\t\t</td><td width=\"190\">\n\t\t<u>Expires:</u> " . $l_exp_text . "\n\t\t</td><td>\n\t\t<u>Status:</u> " . $lb_status . "\n\t\t</td></tr>\n\t\t</table>\n\t\t\n\t\t</td>\n\t\t</tr>"; $tblClass = $tblClass == "tblRowA" ? "tblRowB" : "tblRowA"; } if( !$html ) { $html .= "<tr class=\"" . $tblClass . "\"><td colspan=\"7\"><span style=\"color: gray;\">Currently no active " . $token_label . "s...</span></td></tr>"; } echo $html; echo "</table>\n\n<br><br>\n\n"; } ?> They used to work fine on old server, I don't know what's up with these errors on new one. They're defined somewhere in somefile, there are 800+ files and it's hard to search in each and every. Is there any way that we can make the server look of the actual file where these classes or variables were defined?
Your code was never working well. It is bad written. The reason you did not see errors, in your old server is that you had lower error reporting or the whole error reporting was turned off. When you are developing something you should always develop with turned on error reporting, so you can see your mistakes. The first problem is here if(!is_object($es)) { You check directly if $es is object, but this is wrong, because this statement is at the top of the file, and $es will be aways undefined unless you import it from the global scope, like this: global $es; if(!is_object($es)) { Your second error is because you have referenced wrongly the Forum class: $f = new FOrum(); I suppose it should be: $f = new Forum();
php json not showing Wunderground station list
I'm trying to show a list of all nearby weather stations. I have the code: $json_string = file_get_contents("http://api.wunderground.com/api/8b19ccf6a06c0826/geolookup/conditions/q/Netherlands/Rotterdam.json"); $parsed_json = json_decode($json_string); $stations = $parsed_json->{'location'}->{'nearby_weather_stations'}->{'pws'}->{'station'}; $count = count($stations); for($i = 0; $i < $count; $i++) { $station = $stations[$i]; if (count($station) > 1) { echo "City: " . $station->{'city'} . "\n"; echo "State: " . $station->{'state'} . "\n"; echo "Latitude: " . $station->{'lat'} . "\n"; echo "Longitude: " . $station->{'lon'} . "\n"; } } But currently it's not showing anything, i have searched for examples but i couldn't find any solution fot this problem.
Alternatively, you could use a simple foreach to iterate those values. Consider this example: $json_string = file_get_contents("http://api.wunderground.com/api/8b19ccf6a06c0826/geolookup/conditions/q/Netherlands/Rotterdam.json"); $parsed_json = json_decode($json_string, true); // <-- second parameter to TRUE to use it as an array $desired_values = $parsed_json['location']['nearby_weather_stations']['pws']['station']; foreach($desired_values as $key => $value) { echo "<hr/>"; echo "City: " . $value['city'] . "<br/>"; echo "State: " . $value['state'] . "<br/>"; echo "Latitude: " . $value['lat'] . "<br/>"; echo "Longitude: " . $value['lon'] . "<br/>"; echo "<hr/>"; } Sample Fiddle
Format text to fit in columns in Excel
I have this block of text in an array: "Stefan Olsson" "Kungsvägen" "Skolgatan" xxxx-xx-xx 0735xxxxxx, "Pär Davidsson" "Skolgatan" "Myntvägen" xxxx-xx-xx 0709xxxxxx, I parse this type of content to an CSV-file, for later usage in Excel. However, I want to fromat this text to fit in different columns in excell. So, when I open the CSV-file in Execel, I want the name to be in one column, the address in the column besides etcetc. How can I accomplish this? Should I use PHPExcel? Or could it be done with plain old PHP? Here is my PHP-code $gatunamn = $_POST['gata']; $ort = $_POST['omrade']; $csv_data = array(); $newSpider->fetchPage($gatunamn, $ort, $offset=0); $obj = json_decode($newSpider->html); echo "<div id='rightcontent'><table id='one-column-emphasis'>"; echo "<th><input type='checkbox' name='csv_all' id='csv_all'></th><th>Namn</th><th>Adress</th><th>Adress2</th><th>Adress3</th><th>Personnummer</th><th>Telefonnummer</th><th>Telefonnummer2</th>"; $antal_sidor = round($obj->search->wp->totalHits / $obj->search->wp->pageSize); echo "<td></td>"; foreach($obj->search->wp->features as $fish) //Loopar ut 50st (pageSize) { echo "<tr>"; echo "<td><input type='checkbox' value='csv' class='csv'></td>"; echo "<td>" . $fish->name . "</td>"; $csv_data[] .= utf8_decode($fish->name); foreach($fish->addresses as $ad) { echo "<td>" . $ad->label . " " . $ad->postcode . " " . $ad->area . "</td>"; $csv_data[] .= utf8_decode($ad->label . " " . $ad->postcode . " " . $ad->area); } if(!empty($fish->dateOfBirth)) { $convert_date = substr($fish->dateOfBirth, 0, -3); //Gör om datum från timestamp echo "<td>" . date("Y-m-d", $convert_date) . "</td>"; $convert_datee = date("Y-m-d", $convert_date); $csv_data[] .= $convert_datee; } if(!empty($fish->phoneNumbers)) { foreach($fish->phoneNumbers as $ph) { echo "<td>" . $ph . "</td>"; $csv_data[] .= $ph . ","; } } echo "</tr>"; } echo "</table>"; $j = 0; for($i = 1; $i <= $antal_sidor; $i++) { echo "<a href='curl2.php?gatunamn=$gatunamn&ort=$ort&offset=$j'>" . $i . "</a> "; $j += 100; } echo "</div>"; echo "<div id='debug'><pre>"; var_dump($csv_data); echo "</pre></div>"; } if(isset($_POST['export'])) { $fp = fopen("eniroo.csv","w"); foreach(explode(",", implode("\n",$csv_data)) as $rad) { fputcsv($fp, array(implode(',', str_getcsv($rad, "\n")))); } echo "<div id='csv_info'>"; echo "<a href='eniro.csv'>Hämta CSV-fil</a>"; echo "</div>"; }
// Restructure the original array into rows $myDataArray = array_chunk($myDataArray, 5); // Then write to CSV $fp = fopen('file.csv', 'w'); foreach($myDataArray as $dataRow) { fputcsv($fh, $dataRow); } fclose($fh)
Passing php variable to javascript (cant get it working)
I'm have a problem getting a php variable to my .js file and make it work. This is my php function where I'm trying to pass the variable: function java_scr_preview ($foto) { echo '<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>'; echo '<script type="text/javascript">'; echo 'var pass_this_variable = "'.$foto.'"'; echo '</script>'; echo '<script type="text/javascript" src="ddimgtooltip.js">'; echo '<SCRIPT LANGUAGE="JavaScript">'; echo 'function Preview(url)'; echo '{'; echo "window.open(url,'_blank','location=no,scrollbars=yes,toolbar=no,width=500,height=700')"; echo '}'; echo '</SCRIPT>'; } This is my whole php script (if needed) <?php require ("auth.php"); if (isset($_GET['cmd'])) $cmd = $_GET['cmd']; else $cmd = ""; switch ($cmd) { case "": html_open_std (); ingave_artikel ("", "", "", ""); html_close (); break; case "search": html_open_std (); ingave_artikel ("", "", "", ""); toon_banden (); html_close (); break; case "preview": $foto = $_GET['foto']; toon_preview ($foto); break; } #------------------------------------------------------------ function ingave_artikel ($art1, $art2, $art3, $errormelding) { global $urlphp; global $urlcgi; global $ad; echo "<div id=\"invoeren\">"; echo "<h1>Ingave bandenmaat</h1>\n"; echo "<form method=\"POST\" action=\"?cmd=search\">\n"; echo "<table border=\"0\" cellspacing=\"2\" cellpadding=\"2\">\n"; echo "<tr>\n"; echo "<td>Breedte</td>\n"; echo "<td> </td>\n"; echo "<td>Hoogte</td>\n"; echo "<td> </td>\n"; echo "<td>Diameter</td>\n"; echo "</tr>\n"; echo "<tr>\n"; echo "<td><input type=\"text\" name=\"art1\" value=\"" . $art1 . "\" size=\"5\"></td>\n"; echo "<td>/</td>\n"; echo "<td><input type=\"text\" name=\"art2\" value=\"" . $art2 . "\" size=\"5\"></td>\n"; echo "<td>x</td>\n"; echo "<td><input type=\"text\" name=\"art3\" value=\"" . $art3 . "\" size=\"5\"></td>\n"; echo "</tr>\n"; if (! empty ($errormelding)) echo "<tr><td colspan=\"5\"><font color=\"red\">" . $errormelding . "</td></tr>\n"; echo "<tr>\n"; echo "<td colspan=\"3\">\n"; echo "<input type=\"submit\" value=\"Verwerk\">\n"; echo "</td>\n"; echo "</tr>\n"; echo "</table>\n"; echo "</form>\n"; echo "</div>\n"; } #------------------------------------------------------------ function toon_banden () { global $urlphp; global $urlcgi; global $gateway; java_scr_preview (); $art1 = trim($_POST["art1"]); $art2 = trim($_POST["art2"]); $art3 = trim($_POST["art3"]); if (empty ($art1) || empty ($art3)) { ingave_artikel ($art1, $art2, $art3, "Alle velden ingeven s.v.p."); return (-1); } $f = open_url ($gateway . "?3," . $art1 . $art2 . "R" . $art3); if ($f == NULL) return (-1); $t = 0; $ncol = 4; $ar = explode (PHP_EOL, $f); if (substr($ar[0],0,7) == "*ERROR*") { echo "<p>"; echo "<h1>"; echo "Gateway functions are disabled !" . "<br>"; echo "</p>"; return (-1); } foreach ($ar as $rec) { if ($rec == 0) { continue; } list ($sysnr, $artikel, $merk, $rubriek, $omschrijving, $valuta, $netto, $bruto, $beschikbaar, $foto, $draagvrm, $levid, $garpr, $altpr, $eancode) = explode ("\t", $rec); if ($sysnr == "*END*") break; if ($t == 0) { echo "<table border=0 cellspacing=0 cellpadding=0>"; echo "<tr><td align=center>"; echo "<div id=\"uitkomst\">"; echo "<h1>Overzicht beschikbare voorraad</h1>\n"; echo "<table border=\"0\" cellspacing=\"2\" cellpadding=\"5\">\n"; echo "<td><b>Merk</td>\n"; echo "<td><b>Omschrijving</td>\n"; echo "<td><b>LI/SI</td>\n"; echo "<td align=\"right\"><b>Bruto</td>\n"; echo "<td align=\"right\"><b>Netto " . $valuta . "</td>\n"; echo "<td align=\"right\"><b>Beschikbaar</td>\n"; echo "<td></td>\n"; } ### klantprijs opslag 25 % $klantpr = $netto * 1.25; $klantpr_str = sprintf ("%7.2f", $klantpr); echo "<tr>\n"; echo "<td>" . $merk . "</td>\n"; echo "<td>" . $omschrijving . "</td>\n"; echo "<td>" . $draagvrm . "</td>\n"; echo "<td align=\"right\">" . $bruto . "</td>\n"; echo "<td align=\"right\">" . $klantpr_str . "</td>\n"; echo "<td align=\"right\">" . $beschikbaar . "</td>\n"; if (empty ($foto)) echo "<td></td>\n"; else { echo "<td>"; echo '<a rel="imgtip[2]" href="javascript:Preview'; echo "('?cmd=preview&foto=$foto')"; echo '">'; echo "Foto"; echo '</a>'; echo "</td>\n"; } echo "</tr>\n"; $t++; } if ($t == 0) ingave_artikel ($art1, $art2, $art3, "Geen artikelen gevonden !"); else { echo '</table>'; echo '</div>'; } } #------------------------------------------------------------ function toon_preview ($fotonr) { global $imglarge; html_open_std (); echo '<center>'; echo '<br>'; echo '<img border="0" src="' . $imglarge . '/' . $fotonr . '">'; html_close (); } #------------------------------------------------------------ function toon_selektie ($merk, $model, $type, $diameter) { echo '<table border="0" cellspacing="0" cellpadding="0">'; echo '<tr><td width="70">Merk</td><td><b>' . $merk . '</td></tr>'; echo '<tr><td>Model</td><td><b>' . $model . '</td></tr>'; echo '<tr><td>Type</td><td><b>' . $type . '</td></tr>'; echo '<tr><td>Diameter</td><td><b>' . $diameter . '</td></tr>'; echo '</table>'; echo '<hr>'; } #------------------------------------------------------------ function open_url ($url) { global $login; global $passwd; $ch = curl_init("http://$url"); curl_setopt($ch, CURLOPT_USERPWD, "$login:$passwd"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $file = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_HTTP_CODE); $errno = curl_errno($ch); $error = curl_error($ch); if ($status == 200) { return ($file); } else { echo "<p>"; echo "<h1>"; if ($status == 401) { echo "Authentication failed !"; } else { echo "Errno: " . $errno . "<br>"; echo "Error: " . $error . "<br>"; echo "HTTP status : " . $status . "<br>"; } echo "</p>"; return (NULL); } } #------------------------------------------------------------ function html_open_std () { echo '<html>'; echo '<head>'; echo '<title>Banden uit voorraad leverbaar</title>'; echo '<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">'; echo '<meta name="robots" content="noinclude, nofollow">'; echo '<link rel="stylesheet" href="tyre.css" type="text/css">'; echo '</head>'; echo '<body>'; } #------------------------------------------------------------ function html_close () { echo "</body>"; echo "</html>"; } #------------------------------------------------------------ function java_scr_preview ($foto) { echo '<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>'; echo '<script type="text/javascript">'; echo 'var pass_this_variable = "'.$foto.'"'; echo '</script>'; echo '<script type="text/javascript" src="ddimgtooltip.js">'; echo '<SCRIPT LANGUAGE="JavaScript">'; echo 'function Preview(url)'; echo '{'; echo "window.open(url,'_blank','location=no,scrollbars=yes,toolbar=no,width=500,height=700')"; echo '}'; echo '</SCRIPT>'; } ?> And this is my whole .js file: It is a tooltip script and I want to show my images dynamicly: /* Image w/ description tooltip v2.0 * Created: April 23rd, 2010. This notice must stay intact for usage * Author: Dynamic Drive at http://www.dynamicdrive.com/ * Visit http://www.dynamicdrive.com/ for full source code */ var ddimgtooltip={ tiparray:function(){ var tooltips=[] //define each tooltip below: tooltip[inc]=['path_to_image', 'optional desc', optional_CSS_object] //For desc parameter, backslash any special characters inside your text such as apotrophes ('). Example: "I\'m the king of the world" //For CSS object, follow the syntax: {property1:"cssvalue1", property2:"cssvalue2", etc} tooltips[0]=["red_balloon.gif", "Here is a red balloon<br /> on a white background", {background:"#FFFFFF", color:"black", border:"5px ridge darkblue"}] tooltips[1]=["duck2.gif", "Here is a duck on a light blue background.", {background:"#DDECFF", width:"200px"}] tooltips[2]=["http://www.website.net/preview/test/pass_this_variable"] tooltips[3]=["../dynamicindex17/bridge.gif", "Bridge to somewhere.", {background:"white", font:"bold 12px Arial"}] return tooltips //do not remove/change this line }(), tooltipoffsets: [20, -30], //additional x and y offset from mouse cursor for tooltips //***** NO NEED TO EDIT BEYOND HERE tipprefix: 'imgtip', //tooltip ID prefixes createtip:function($, tipid, tipinfo){ if ($('#'+tipid).length==0){ //if this tooltip doesn't exist yet return $('<div id="' + tipid + '" class="ddimgtooltip" />').html( '<div style="text-align:center"><img src="' + tipinfo[0] + '" /></div>' + ((tipinfo[1])? '<div style="text-align:left; margin-top:5px">'+tipinfo[1]+'</div>' : '') ) .css(tipinfo[2] || {}) .appendTo(document.body) } return null }, positiontooltip:function($, $tooltip, e){ var x=e.pageX+this.tooltipoffsets[0], y=e.pageY+this.tooltipoffsets[1] var tipw=$tooltip.outerWidth(), tiph=$tooltip.outerHeight(), x=(x+tipw>$(document).scrollLeft()+$(window).width())? x-tipw-(ddimgtooltip.tooltipoffsets[0]*2) : x y=(y+tiph>$(document).scrollTop()+$(window).height())? $(document).scrollTop()+$(window).height()-tiph-10 : y $tooltip.css({left:x, top:y}) }, showbox:function($, $tooltip, e){ $tooltip.show() this.positiontooltip($, $tooltip, e) }, hidebox:function($, $tooltip){ $tooltip.hide() }, init:function(targetselector){ jQuery(document).ready(function($){ var tiparray=ddimgtooltip.tiparray var $targets=$(targetselector) if ($targets.length==0) return var tipids=[] $targets.each(function(){ var $target=$(this) $target.attr('rel').match(/\[(\d+)\]/) //match d of attribute rel="imgtip[d]" var tipsuffix=parseInt(RegExp.$1) //get d as integer var tipid=this._tipid=ddimgtooltip.tipprefix+tipsuffix //construct this tip's ID value and remember it var $tooltip=ddimgtooltip.createtip($, tipid, tiparray[tipsuffix]) $target.mouseenter(function(e){ var $tooltip=$("#"+this._tipid) ddimgtooltip.showbox($, $tooltip, e) }) $target.mouseleave(function(e){ var $tooltip=$("#"+this._tipid) ddimgtooltip.hidebox($, $tooltip) }) $target.mousemove(function(e){ var $tooltip=$("#"+this._tipid) ddimgtooltip.positiontooltip($, $tooltip, e) }) if ($tooltip){ //add mouseenter to this tooltip (only if event hasn't already been added) $tooltip.mouseenter(function(){ ddimgtooltip.hidebox($, $(this)) }) } }) }) //end dom ready } } //ddimgtooltip.init("targetElementSelector") ddimgtooltip.init("*[rel^=imgtip]") And this rule: tooltips[2]=["http://www.website.net/preview/test/pass_this_variable"] Should show the variable $foto... Anyone can help me to fix this? Working 2 days on it now and cant figure it out... Update I've tried some things and I manage to get some info to my javascript like this: .php file function java_scr_preview () { echo '<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>'; ?> <?php $foto = "image.jpg"; ?> <script type="text/javascript"> var foto = "<?= $foto ?>"; </script> <?php echo '<script type="text/javascript" src="ddimgtooltip.js">'; echo '<SCRIPT LANGUAGE="JavaScript">'; echo 'function Preview(url)'; echo '{'; echo "window.open(url,'_blank','location=no,scrollbars=yes,toolbar=no,width=500,height=700')"; echo '}'; echo '</SCRIPT>'; } ?> .js file tooltips[2]=["http://www.website.net/preview/test/"+ foto]; alert(tooltips[2]); This is showing http://www.website.net/preview/test/image.jpg in my alert... But when I'm doing it like this: $foto = $_GET["foto"]; I'm getting an error : Notice: Undefined index: foto in /var/www/html/website.nl/test/test.php on line 291 And in my alert only http://www.website.net/preview/test/... How should I pass my dynamic variable?
Change tooltips[2]=["http://www.website.net/preview/test/pass_this_variable"] to tooltips[2]=["http://www.website.net/preview/test/" + pass_this_variable] You were not using the variable you were just passing text. Simplified example here
In function toon_banden() you call java_scr_preview() and you are not passing the expected arg.