My English is poor. I'm sorry if there is anything rude.
Thank you for taking the time to read my question.
When I use PHP function json_decode(), i get null and json_last_error() throws 4.
Thanks for helping!
my PHP code is
$str = file_get_contents("cache.txt");
$str = htmlspecialchars_decode($str);
$arr = json_decode($str, true);
print_r($arr);
echo $errorinfo = json_last_error();
the content of File named cache.txt is:
[[1,[0,"wWfxgeyEgrRf1M",["https://encrypted-tbn0.gstatic.com/images?q\u003dtbn%3AANd9GcTFekou1VcAkVW23s69_Q53CsUJD0syjACwY0jHbRYcRIcr5cyp",225,225],["https://www.hijordan.com/image/cache/catalog/Jordan-Retro-1/Jordan-Retro-1-16-1080x1080.jpg",1080,1080],null,2,"rgb(160,42,51)",null,false,{"2001":[null,null,null,21,18,3,3,null,null,null,[]],"2003":[null,"M3A7LEiRdcA0DM","https://www.aljadid.com/efabshop/air-jordan-retro-1-red-black-white-p-16.html","Nike Air Jordan Retro 1 Red Black White - Buy Air Jordan 1 Retro ...",null,false,null,null,null,false,null,null,"Al Jadid",null,null,null,null,null,null,null,null,null,false,false,false,{"26":[null,2]}],"2006":[null,[4.0,null,"Air Jordan Retro 1 red black white",null,"A stepping stone to the world of Air Jordan is the Original air jordan 1 (I) White Black Red, which was worn by Michael Jordan the majority of the ...",null,true,5,60.85,"USD"]],"2008":[null,"Nike Air Jordan Retro 1 Red Black White ..."],"183836587":["aljadid.com"]}],null,[177,158,null,null,null,177,177,null,null,-10,null,null,false,true,null,null,[]],0,null,null,"wWfxgeyEgrRf1M",1,null,null,null,null,[[1580879352798185,178652430,3708684377],null,2]],[1,[0,"sFUMQKdZQFRaGM",["https://encrypted-tbn0.gstatic.com/images?q\u003dtbn%3AANd9GcSV5L3VvYWthX-IG9QO5QfLN_6eLvA687_og435LmF6_5NmGSI4",225,225],["https://www.hijordan.com/image/cache/catalog/air-jordan-12/air-jordan-12-49-1080x1080.jpg",1080,1080],null,2,"rgb(160,58,51)",null,false,{"2001":[null,null,null,21,18,3,6,null,null,null,[]],"2003":[null,"pTPqQEjGfZF7JM","https://togaf9-cert.opengroup.org/bcabshop/air-jordan-12-retro-black-varsity-red-p-1138.html","Air Jordan 12 Retro Black Varsity Red , Price: $89.90 - Air Jordan ...",null,false,null,null,null,false,null,null,"TOGAF? 9 Certification",null,null,null,null,null,null,null,null,null,false,false,false,{"26":[null,2]}],"2006":[null,[4.0,null,"Air Jordan 12 Retro Black Varsity Red","Nike","You should not miss the chance if you have not got one like the Air Jordan 12 Retro Black Varsity Red. Fine craftsmanship with premium materials like ...",null,true,5,89.9,"USD"]],"2008":[null,"Air Jordan 12 Retro Black Varsity Red ..."],"183836587":["togaf9-cert.opengroup.org"]}],],]
Related
I'm making a form text input box for an inventory list. I type everything into the form and it breaks everything down to be put into SQL(not at the SQL part yet).
Input would look something like this
5-1 1/2 black 90° sch 40 (have 10 of the sch 80 ones)
amount - size - fitting name ( comments)
I got everything in their own variable now I just need to remove the "(comments)" part from the fitting name. str_replace should do the trick but it seems to only work "some times" ? I'm not sure why it doesn't always work. The picture below show that it only worked 2 times. As for my regex, I'm really bad at them. lol Thanks for any help you can give with my little problem.
foreach ($components as $value) {
$value=stripslashes($value);
// get rid of empty lines
if (empty($value)) { continue; }
// will Split the amount of fittings from the value.
$quantity = explode("-", $value);
//Will split the name of the fitting and also give the size of the fittings.
$test=preg_split('/([a-w]|[A-W])/', $quantity[1],2, PREG_SPLIT_DELIM_CAPTURE);
//split the comments from the fitting name.
$comments = explode("(", $test[2]);
//removes the remaining ) from the left side
$comments =preg_replace("/\)/", "" , $comments[1]);
if(!empty($comments)) {
$fitting_name = str_replace("($comments)","", $test[1].$test[2]);
}else{
$fitting_name = $test[1].$test[2];
}
// The table format is just to make sure everything is working right before inputting into SQL
echo "
<tr>
<td>$value</td>
<td>". $quantity[0] ."</td>
<td>$test[0]</td>
<td>$fitting_name</td>
<td>$comments </td>
</tr>
<tr>
";
}
echo "</tr>
</table>";
}
Input
0-1/2 PP union
1- 1 1/2x1 1/4 copper PP fitting red
9- 1 1/2" copper PP 90°
5-2" copper PP 90° (have 10 of the sch 80 ones)
13-2" copper PP Tee (have 10 of the sch 80 ones)
10-1*1*3/4 copper PP tee
60- 3/4" PP cap and chain value
50 - 3/4" PP value (we only have 4 more)
19- 3/4" threaded cap and chain value
0-2" threaded value
0- 2 1/2" threaded value (have 10 of the sch 80 ones)
5- 3/4" black Street 90°
0 - 3/4 black union
0- 1" black union
0-1" black tee
1 - 1 1/2 black union
6-1 1/4 black cap
7-1 1/2" * 1" black bushing
3 - 1 1/2 black coupling
5-1 1/2 black 90° sch 40? (have 10 of the sch 80 ones)
4 - 3/8" rod 6'
4-3/8" rod 10'
6 - 1/2" rod 6'
0-5/8" rod 6"
0-5/8" rod 10'
0-3/4 rod 6'
2 - 1" rod 6'(have 10 of the sch 80 ones)
I would first remove the comment before doing any parsing, to cleanse the input.
You can extract it with a RegEx :
\s*\(.*?\)
\s* matches 0 or more white spaces
\( matches a parenthesis
.*? matches any characters (lazy match)
\) matches a parenthesis
Now, you can replace this by an empty string :
<?php
$input = [
"0-1/2 PP union ",
"1- 1 1/2x1 1/4 copper PP fitting red",
"9- 1 1/2\" copper PP 90°",
"5-2\" copper PP 90° (have 10 of the sch 80 ones) ",
"13-2\" copper PP Tee (have 10 of the sch 80 ones) ",
"10-1*1*3/4 copper PP tee",
"",
"",
"60- 3/4\" PP cap and chain value ",
"50 - 3/4\" PP value (we only have 4 more)",
"19- 3/4\" threaded cap and chain value ",
"0-2\" threaded value ",
"0- 2 1/2\" threaded value (have 10 of the sch 80 ones) ",
"",
"",
"5- 3/4\" black Street 90°",
"0 - 3/4 black union ",
"0- 1\" black union ",
"0-1\" black tee ",
"1 - 1 1/2 black union ",
"6-1 1/4 black cap",
"7-1 1/2\" * 1\" black bushing",
"3 - 1 1/2 black coupling ",
"5-1 1/2 black 90° sch 40? (have 10 of the sch 80 ones) ",
"",
"",
"",
"4 - 3/8\" rod 6'",
"4-3/8\" rod 10'",
"6 - 1/2\" rod 6'",
"0-5/8\" rod 6\"",
"0-5/8\" rod 10'",
"0-3/4 rod 6'",
"2 - 1\" rod 6'(have 10 of the sch 80 ones) "
];
foreach ($input as $value)
{
$newValue = preg_replace("#\s*\(.*?\)#", "", $value);
echo $newValue . PHP_EOL;
}
Output :
0-1/2 PP union
1- 1 1/2x1 1/4 copper PP fitting red
9- 1 1/2" copper PP 90°
5-2" copper PP 90°
13-2" copper PP Tee
10-1*1*3/4 copper PP tee
60- 3/4" PP cap and chain value
50 - 3/4" PP value
19- 3/4" threaded cap and chain value
0-2" threaded value
0- 2 1/2" threaded value
5- 3/4" black Street 90°
0 - 3/4 black union
0- 1" black union
0-1" black tee
1 - 1 1/2 black union
6-1 1/4 black cap
7-1 1/2" * 1" black bushing
3 - 1 1/2 black coupling
5-1 1/2 black 90° sch 40?
4 - 3/8" rod 6'
4-3/8" rod 10'
6 - 1/2" rod 6'
0-5/8" rod 6"
0-5/8" rod 10'
0-3/4 rod 6'
2 - 1" rod 6'
Try it yourself
Plese try changing the following line
$fitting_name = str_replace("($comments)","", $test[1].$test[2]);
to
$fitting_name = str_replace("(" . trim($comments).")","", $test[1].$test[2]);
and see the effect. Please let us know the result.
have a API call that gets JSON data with the following headers and info, need the php code that would display the below data in a table format:
the API call is: https://XXXXXXXXXXXXXXX.com/service/price/all?token=XXXXXXXXXXXXXXXXXXXXXXX
any help? I am a beginner.
[{"SKU":"CGP-15-GR-2017","Name":"2017 15 Grams Chinese Gold Panda Coin 200 Yuan BU Sealed","Metal":"Gold","ProductFamily":"Current Year Gold Coins","AssetClass":"Gold Bullion","Ounces":0.482315112540193,"Cogs":962.25,"Bid":907.52,"Ask":1042.34,"BaseCurrency":"USD","RetailShipping":0.0,"WholesaleShipping":0.0},{"SKU":"25-OZ-ATB-SET-2010","Name":"2010 America the Beautiful 5 oz Silver Bullion Coin Set","Metal":"Silver","ProductFamily":"ATB Bullion Program","AssetClass":"Silver Bullion","Ounces":25.0,"Cogs":779.16,"Bid":574.16,"Ask":1330.33,"BaseCurrency":"USD","Description":"25-OZ-ATB-SET-2010","RetailShipping":0.0,"WholesaleShipping":0.0},{"SKU":"PS-1-GR-PLAT-BAR","Name":"1 Gram Pamp Suisse Platinum Bar 999 Fine With Assay","Metal":"Platinum","ProductFamily":"Platinum Bullion","AssetClass":"Platinum","Ounces":0.03215,"Cogs":34.92,"Bid":27.6,"Ask":48.8,"BaseCurrency":"USD","Description":"1-PS-1-GR-PLAT-BAR","RetailShipping":0.0,"WholesaleShipping":0.0},{"SKU":"40-WQ-ROLL-BU","Name":"$10 Washington Quarters - 90% Silver 40-Coin Roll (BU)","Metal":"Silver","ProductFamily":"90% Junk Silver","AssetClass":"Silver Bullion","Ounces":7.15,"Cogs":165.64,"Bid":164.21,"Ask":234.67,"BaseCurrency":"USD","RetailShipping":0.0,"WholesaleShipping":0.0},{"SKU":"GIH-$10-NGCMS64-1932","Name":"GIH-$10-NGCMS64-1932","Metal":"Gold","ProductFamily":"Current Year Gold Coins","AssetClass":"Gold Bullion","Ounces":0.5,"Cogs":943.3,"Bid":990.8,"Ask":1865.03,"BaseCurrency":"USD","RetailShipping":0.0,"WholesaleShipping":0.0},{"SKU":"CGP-10th-2012","Name":"2012 1/10 oz Chinese Gold Panda Coin BU Sealed","Metal":"Gold","ProductFamily":"Current Year Gold Coins","AssetClass":"Gold Bullion","Ounces":0.1,"Cogs":222.62,"Bid":188.16,"Ask":387.52,"BaseCurrency":"USD","Description":"CGP-10th-2012","RetailShipping":0.0,"WholesaleShipping":0.0},{"SKU":"5-OZ-ATB--MBRNP-2020","Name":"2020 5 oz Silver ATB Marsh-Billings-Rockefeller National Park","Metal":"Silver","ProductFamily":"ATB Bullion Program","AssetClass":"Silver Bullion","Ounces":5.0,"Cogs":135.83,"Bid":114.83,"Ask":156.87,"BaseCurrency":"USD","RetailShipping":0.0,"WholesaleShipping":0.0},{"SKU":"SAK-Tenth-NGCPF69-2008","Name":"2008 South Africa 1/10 oz Gold Proof Krugerrand NGC PF 69 DCAM","Metal":"Gold","ProductFamily":"Current Year Gold Coins","AssetClass":"Gold Bullion","Ounces":0.1,"Cogs":188.66,"Bid":188.16,"Ask":279.41,"BaseCurrency":"USD","Description":"SAK-OUNCE-1977","RetailShipping":0.0,"WholesaleShipping":0.0},{"SKU":"1-OUNCE-AGE-1987","Name":"1987 1 oz Gold American Eagle Coin Brand New BU","Metal":"Gold","ProductFamily":"Current Year Gold Coins","AssetClass":"Gold
You can put the JSON data into an array and then iterate it with a foreach()
$arr = json_decode(JSON_DATA_FROM_API);//The data from your api
<table>
<tr>
<th scope="col">COL1</th>
<th scope="col">COL2</th>
<th scope="col">COL3</th>
<th scope="col">COl4</th>
</tr>
foreach($arr as $item) {
<tr>
<td>$item['SKU']</td>
<td>$item['Name']</td>
<td>$item['Metal']</td>
<td>$item['ProductFamily']</td>
</tr>
}
</table>
I try to make a virutal money system and dont get the "number_format"
I want it like the number "7951753" and want that output:
795 17 53
Other example:
$money = 10001;
1 0 1
How I can make that?
You may use substr
$mynumber=7951753;
echo substr($mynumber, 0, 3)." Gold ". substr($mynumber, 3, 2)." Silver " . substr($mynumber, 5, 2)." Bronze ";
above code produces output:-
795 Gold 17 Silver 53 Bronze
You may do same with 10001 to get 1 Gold 0 Silver 1 Bronze :)
Have a try!
Sorry, display fail on posting that here:
Number: 7951753
Output: 795 Gold 17 Silver 53 Bronze
Other example:
Number: 10001
Output: 1 Gold 0 Silver 1 Bronze
i am much confused at this point regarding the csv file creation and insert data in the database.
suppose i have below text data - that is of 45000 record set, i am posting dew of them below.
Winged Wheels in France, by Michael Myers Shoemaker 45790
A Battle Fought on Snow Shoes, by Mary Cochrane Rogers 45789
The German Classics of the Nineteenth and Twentieth Centuries, 45788
Volume 11, by Friedrich Spielhagen, Theodor Storm,
Wilhelm Raabe, Marion D. Learned and Ewald Eiserhardt
[Subtitle: Masterpieces of German Literature
Translated Into English]
Zofloya ou le Maure, Tomes 1-4, by Charlotte Dacre 45787
[Subtitle: Histoire du XVe si?cle]
[Language: French]
Their Majesties as I Knew Them, by Xavier Paoli 45786
[Subtitle: Personal Reminiscences of the
Kings and Queens of Europe]
[Translator: Alexander Teixeira de Mattos]
New York Times Current History: The European War, Vol. 8, 45785
Pt. 2, No. 1, July 1918, by Various
Gallery of Comicalities, by Robert Cruikshank, 45784
George Cruikshank and Robert Seymour
[Subtitle: Embracing Humorous Sketches]
Katri, by Emil Nervander 45783
[Subtitle: Kertomus 17 vuosi-sadasta]
[Language: Finnish]
The Little Brown Jug at Kildare, by Meredith Nicholson 45782
[Illustrator: James Montgomery Flagg]
Beaumont & Fletcher's Works (6 through 10), by Francis Beaumont 45781
and John Fletcher
[Subtitle: The Queen of Corinth; Bonduca; The Knight of the
Burning Pestle; Loves Pilgrimage; The Double Marriage]
Beaumont & Fletcher's Works (1 through 5), by Francis Beaumont 45780
and John Fletcher
[Subtitle: A Wife for a Month; The Lovers Progress;
The Pilgrim; The Captain; The Prophetess]
The Washington Historical Quarterly, Volume V, 1914, by Various 45779
[Editor: Edmond S. Meany]
Minstrelsy of the Scottish Border Volume III of 3, by Walter Scott 45778
[Subtitle: Consisting of Historical and Romantic Ballads,
Collected In the Southern Counties of Scotland; With
a Few Of Modern Date, Founded Upon Local Tradition.
In Three Volumes. Vol. III]
What i want is simply insert Winged Wheels in France, by Michael Myers Shoemaker in one column and 45790 in other column of CSV. then i will be able to add them to my database.
moreover, e.g,
The German Classics of the Nineteenth and Twentieth Centuries,
Volume 11, by Friedrich Spielhagen, Theodor Storm,
Wilhelm Raabe, Marion D. Learned and Ewald Eiserhardt
[Subtitle: Masterpieces of German Literature
Translated Into English]
i want to insert above text in this way:
The German Classics of the Nineteenth and Twentieth Centuries,
Volume 11, by Friedrich Spielhagen, Theodor Storm,
Wilhelm Raabe, Marion D. Learned and Ewald Eiserhardt
means no this portion:
[Subtitle: Masterpieces of German Literature
Translated Into English]
the ", by" should also omitted and so my new data would be like this. so actually i need three columns in the csv.
1 | Winged Wheels in France | Michael Myers Shoemaker | 45790
2 | The German Classics of the Nineteenth and Twentieth Centuries,
Volume 11 | Friedrich Spielhagen, Theodor Storm,
Wilhelm Raabe, Marion D. Learned and Ewald Eiserhardt | 45789
Please help in getting it inserted in excel file and create csv from it.
thank you all.
do like this
(not tested)
$f = file_get_contents('yourtextfile.txt');
$f = preg_replace('/\[(.*?)\]/s','',$f);
$f = str_replace(array("\n", "\r"), '', $f);
file_put_contents('temp.txt',$f);
$file = file('temp.txt');
foreach($file as $key => $line){
if($line!=null || $line!='')
{
mysqli_query($connection,"insert into table1(column1) values('$line')");
}
}
edit
$f = file_get_contents('tt.txt');
$f = preg_replace('/\[(.*?)\]/s','',$f);
$keywords = preg_split("/[ ]{15}/", $f);
print_r(array_filter($keywords));
i'm still not clear,whether you have those numbers in your file or you have just mentioned it there!!
I've been noticing some odd behavior while experimenting with benchmarking SplFixedArrays. Take this little snippet of code, for instance...
<?php
$splFixedArray = new \SplFixedArray( 100000 );
echo number_format( memory_get_usage() ) . PHP_EOL;
$variable = 'Truffaut single-origin coffee wayfarers, church-key asymmetrical 90\'s trust fund hashtag before they sold out thundercats photo booth. Godard sustainable roof party keffiyeh, Odd Future chillwave mlkshk kogi VHS leggings hoodie art party next level dreamcatcher yr. Blog american apparel aesthetic tattooed farm-to-table, stumptown viral whatever mixtape raw denim Williamsburg skateboard flexitarian actually tofu. Echo Park lomo disrupt PBR, jean shorts irony fingerstache blog kale chips. Street art iPhone PBR fingerstache Bushwick Cosby sweater. McSweeney\'s mumblecore semiotics, twee quinoa tofu +1 fingerstache pop-up. Echo Park bitters disrupt irony. Truffaut single-origin coffee wayfarers, church-key asymmetrical 90\'s trust fund hashtag before they sold out thundercats photo booth. Godard sustainable roof party keffiyeh, Odd Future chillwave mlkshk kogi VHS leggings hoodie art party next level dreamcatcher yr. Blog american apparel aesthetic tattooed farm-to-table, stumptown viral whatever mixtape raw denim Williamsburg skateboard flexitarian actually tofu. Echo Park lomo disrupt PBR, jean shorts irony fingerstache blog kale chips. Street art iPhone PBR fingerstache Bushwick Cosby sweater.';
var_dump( $variable );
for( $i = 0; $i < 100000; $i++ )
{
$splFixedArray[ $i ] = $variable;
}
echo number_format( memory_get_usage() );
Which outputs...
1,032,080
string(1209) "Truffaut single-origin coffee wayfarers, church-key asymmetrical 90's trust fund hashtag before they sold out thundercats photo booth. Godard sustainable roof party keffiyeh, Odd Future chillwave mlkshk kogi VHS leggings hoodie art party next level dreamcatcher yr. Blog american apparel aesthetic tattooed farm-to-table, stumptown viral whatever mixtape raw denim Williamsburg skateboard flexitarian actually tofu. Echo Park lomo disrupt PBR, jean shorts irony fingerstache blog kale chips. Street art iPhone PB"...
1,032,384
Now, let's add a simple random integer onto the end while in the for loop...
<?php
$splFixedArray = new \SplFixedArray( 100000 );
echo number_format( memory_get_usage() ) . PHP_EOL;
$variable = 'Truffaut single-origin coffee wayfarers, church-key asymmetrical 90\'s trust fund hashtag before they sold out thundercats photo booth. Godard sustainable roof party keffiyeh, Odd Future chillwave mlkshk kogi VHS leggings hoodie art party next level dreamcatcher yr. Blog american apparel aesthetic tattooed farm-to-table, stumptown viral whatever mixtape raw denim Williamsburg skateboard flexitarian actually tofu. Echo Park lomo disrupt PBR, jean shorts irony fingerstache blog kale chips. Street art iPhone PBR fingerstache Bushwick Cosby sweater. McSweeney\'s mumblecore semiotics, twee quinoa tofu +1 fingerstache pop-up. Echo Park bitters disrupt irony. Truffaut single-origin coffee wayfarers, church-key asymmetrical 90\'s trust fund hashtag before they sold out thundercats photo booth. Godard sustainable roof party keffiyeh, Odd Future chillwave mlkshk kogi VHS leggings hoodie art party next level dreamcatcher yr. Blog american apparel aesthetic tattooed farm-to-table, stumptown viral whatever mixtape raw denim Williamsburg skateboard flexitarian actually tofu. Echo Park lomo disrupt PBR, jean shorts irony fingerstache blog kale chips. Street art iPhone PBR fingerstache Bushwick Cosby sweater.';
var_dump( $variable );
for( $i = 0; $i < 100000; $i++ )
{
$splFixedArray[ $i ] = $variable . rand();
}
echo number_format( memory_get_usage() );
Which results in this...
1,034,320
string(1209) "Truffaut single-origin coffee wayfarers, church-key asymmetrical 90's trust fund hashtag before they sold out thundercats photo booth. Godard sustainable roof party keffiyeh, Odd Future chillwave mlkshk kogi VHS leggings hoodie art party next level dreamcatcher yr. Blog american apparel aesthetic tattooed farm-to-table, stumptown viral whatever mixtape raw denim Williamsburg skateboard flexitarian actually tofu. Echo Park lomo disrupt PBR, jean shorts irony fingerstache blog kale chips. Street art iPhone PB"...
129,834,272
What I'm curious about is why function calls are resulting in stacked memory usage. Is it normal that memory would not be freed up after the iteration?
This behavior is expected.
In the first case, you are storing the same value multiple times, which can be implemented as a single instance of the value and a batch of references to it, with a copy-on-write semantic for cases when the value at a given array index is changed.
In the second case, you are storing many different values, which can't be handled the same way; memory must be allocated for the full contents of each value, which results in the difference you see in memory consumption between the two cases.