This question already has answers here:
How to delete a line from the file with php?
(10 answers)
Closed last year.
I have a css file with this content:
#firstdiv { width:100%; height:200px; }
#seconddiv { width:80%; height:70px; }
#thirddiv { width:80%; height:70px; }
#firstdiv { color:red; background:yellow; }
#seconddiv { color:red; background:green; }
#firstdiv { border:3px solid black; border-rdius:5px; }
How can I remove all #firstdiv css properties using php?
This is my desired output:
#seconddiv { width:80%; height:70px; }
#thirddiv { width:80%; height:70px; }
#seconddiv { color:red; background:green; }
The most easy way would to split the file based on newlines and then check for each row whether it starts with the string you don't want and finally save the file to the location.
$filelocation = "/path/to/file"; //please update for your situation
$csscontents = file_get_contents($filelocation);
$lines = explode(PHP_EOL,$csscontents);
$csscontents = '';
foreach($lines as $line) {
if (substr($line,0,9) !== "#firstdiv") $csscontents .= $line . PHP_EOL;
}
file_put_contents($filelocation,$csscontents);
In case there are multiple selectors on one line, you need to do this
$filelocation = "/path/to/file"; //please update for your situation
$csscontents = file_get_contents($filelocation);
$lines = explode('}',$csscontents);
$csscontents = '';
foreach($lines as $line) {
if (substr(preg_replace('/\s+/', '',$line),0,9) !== "#firstdiv" AND !empty($line) AND !ctype_space($line)) $csscontents .= $line . "}";
}
file_put_contents($filelocation,$csscontents);
I'm trying to parse a CSS file with the Raphael Schweikert's lib Sabberworm\PHP-CSS-PARSE
But I'm blocked with object manipulations. What I'm trying to do is to convert this css file:
.header {
background: #000;
}
.footer, .wrapper {
background: #ebebeb;
}
In a PHP/JSON like format:
'.header' => "background: #000;",
'.footer' => "background: #ebebeb;",
'.wrapper' => "background: #ebebeb;"
What i did:
<?php
require 'vendor/autoload.php';
$oCssParser = new Sabberworm\CSS\Parser(file_get_contents('style.css'));
$oCssDocument = $oCssParser->parse();
$selectors=$oCssDocument->getAllRuleSets();
...
but how to loop after ? The structure of the object is not easy for a neewbe like me...
(This should be a comment, but with the code this is better readable).
I'm not familiar with PHP-CSS-PARSE, but I have one observation: I would assume
.footer .wrapper {
background: #ebebeb;
}
would become '.footer .wrapper' => "background: #ebebeb;".
If you want
'.footer' => "background: #ebebeb;",
'.wrapper' => "background: #ebebeb;"
then the CSS would have to be
.footer, .wrapper {
background: #ebebeb;
}
(notice the comma) or have to have separate rules.
I was lazy yesterday...
<?php
require 'vendor/autoload.php';
$oCssParser = new Sabberworm\CSS\Parser(file_get_contents('style.css'));
$oCssDocument = $oCssParser->parse();
foreach ($oCssDocument->getAllRuleSets() as $oRuleSet) {
$sSelector = $oRuleSet->getSelectors();
foreach ($sSelector as $currentSelector) {
$sSelector = $currentSelector->getSelector();
echo "\r\n\"$sSelector\" = \"";
foreach( $oRuleSet->getRules() as $sRules) {
echo "$sRules ";
}
echo "\"";
}
}
wich renders
".header" = "background: #000; "
".footer" = "background: #ebebeb; "
".wrapper" = "background: #ebebeb; "
This question already has answers here:
Is there a pretty print for PHP?
(31 answers)
Closed 7 months ago.
I have a simple $_GET[] query var set for showing testing data when pulling down queries from the DB.
<?php if($_GET['test']): ?>
<div id="test" style="padding: 24px; background: #fff; text-align: center;">
<table>
<tr style="font-weight: bold;"><td>MLS</td></tr>
<tr><td><?php echo KEY; ?></td></tr>
<tr style="font-weight: bold;"><td>QUERY</td></tr>
<tr><td><?php echo $data_q; ?></td></tr>
<tr style="font-weight: bold;"><td>DATA</td></tr>
<tr><td><?php var_dump($data); ?></td></tr>
</table>
</div>
<?php endif; ?>
When I do var_dump, as expected it's this big array string that is all smushed together. Is there a way to add in line breaks at least for this or display the var_dump in a way that's more readable? I'm open to jQuery suggestions on manipulating the string after it's posted.
I really love var_export(). If you like copy/paste-able code, try:
echo '<pre>' . var_export($data, true) . '</pre>';
Or even something like this for color syntax highlighting:
highlight_string("<?php\n\$data =\n" . var_export($data, true) . ";\n?>");
Reusable function:
function highlight_array($array, $name = 'var') {
highlight_string("<?php\n\$$name =\n" . var_export($array, true) . ";\n?>");
}
You can do the same with print_r(). For var_dump() you would just need to add the <pre> tags:
echo '<pre>';
var_dump($data);
echo '</pre>';
Try xdebug extension for php.
Example:
<?php var_dump($_SERVER); ?>
Outputs:
Use preformatted HTML element
echo '<pre>';
var_dump($data);
echo '</pre>';
I have make an addition to #AbraCadaver answers.
I have included a javascript script which will delete php starting and closing tag.
We will have clean more pretty dump.
May be somebody like this too.
function dd($data){
highlight_string("<?php\n " . var_export($data, true) . "?>");
echo '<script>document.getElementsByTagName("code")[0].getElementsByTagName("span")[1].remove() ;document.getElementsByTagName("code")[0].getElementsByTagName("span")[document.getElementsByTagName("code")[0].getElementsByTagName("span").length - 1].remove() ; </script>';
die();
}
Result before:
Result After:
Now we don't have php starting and closing tag
I don't seem to have enough rep to close this as a duplicate, but it is one if someone else can do that. I posted the same thing over at A more pretty/informative Var_dump alternative in PHP? but for the sake of saving time, I'll copy/paste it here too:
I had to add another answer here because I didn't really want to go through the steps in the other solutions. It is extremely simple and requires no extensions, includes etc and is what I prefer. It's very easy and very fast.
First just json_encode the variable in question:
echo json_encode($theResult);
Copy the result you get into the JSON Editor at http://jsoneditoronline.org/ just copy it into the left side pane, click Copy > and it pretty prints the JSON in a really nice tree format.
To each their own, but hopefully this helps some others have one more nice option! :)
Here's an alternative, actively maintained open source var_dump on steroids:
https://github.com/php-sage/sage
It works with zero set up and is more useable than Xdebug's var_dump and symfony/var-dumper.
Example which bypasses the dumped object size limit on the fly with Kint:
require 'sage.phar';
+d( $variable ); // append `+` to the dump call
Here's a screenshot:
If it's "all smushed together" you can often give the ol' "view source code" a try. Sometimes the dumps, messages and exceptions seem like they're just one long string when it turns out that the line breaks simply don't show. Especially XML trees.
Alternatively, I've once created a small little tool called InteractiveVarDump for this very purpose. It certainly has its limits but it can also be very convenient sometimes. Even though it was designed with PHP 5 in mind.
The best what and easiest way to get nice var_dump is use xDebug (must have for any php dev)
Debian way install
In console: apt-get install php-xdebug
after that you should open php.ini (depends on which stack you use) for it's /etc/php/7.0/fpm/php.ini
Search for display_errors
set same -> display_errors = On
Check html_errors in same file a little bit below, it's also must be On
Save and exit
After open /etc/php/7.0/fpm/conf.d/20-xdebug.ini
And add to the end:
```
xdebug.cli_color=1
```
Save and exit.
A lot other available option and documentation for xdebug can be founded here.
https://xdebug.org/docs/
Good luck and Have Fun !!!
Result
You could use this one debugVar() instead of var_dump()
Check out: https://github.com/E1NSER/php-debug-function
Here is my function to have a pretty var_dump. Combined with Xdebug, it helps a lot to have a better view of what we are dumping.
I improved a bit the display of Xdebug (give some space around, separator between values, wrap long variables, etc).
When you call the function, you can set a title, a background, a text color to distinguish all your var_dump in a page.
Or not ;)
/**
* Pretty var_dump
* Possibility to set a title, a background-color and a text color
*/
function dump($data, $title="", $background="#EEEEEE", $color="#000000"){
//=== Style
echo "
<style>
/* Styling pre tag */
pre {
padding:10px 20px;
white-space: pre-wrap;
white-space: -moz-pre-wrap;
white-space: -pre-wrap;
white-space: -o-pre-wrap;
word-wrap: break-word;
}
/* ===========================
== To use with XDEBUG
=========================== */
/* Source file */
pre small:nth-child(1) {
font-weight: bold;
font-size: 14px;
color: #CC0000;
}
pre small:nth-child(1)::after {
content: '';
position: relative;
width: 100%;
height: 20px;
left: 0;
display: block;
clear: both;
}
/* Separator */
pre i::after{
content: '';
position: relative;
width: 100%;
height: 15px;
left: 0;
display: block;
clear: both;
border-bottom: 1px solid grey;
}
</style>
";
//=== Content
echo "<pre style='background:$background; color:$color; padding:10px 20px; border:2px inset $color'>";
echo "<h2>$title</h2>";
var_dump($data);
echo "</pre>";
}
function var_view($var)
{
ini_set("highlight.keyword", "#a50000; font-weight: bolder");
ini_set("highlight.string", "#5825b6; font-weight: lighter; ");
ob_start();
highlight_string("<?php\n" . var_export($var, true) . "?>");
$highlighted_output = ob_get_clean();
$highlighted_output = str_replace( ["<?php","?>"] , '', $highlighted_output );
echo $highlighted_output;
die();
}
There is a Symfony package for this: https://symfony.com/doc/current/components/var_dumper.html.
Here is a function I made for showing arrays in a nice way:
function nicevar($var,$title=''){
if(is_array($var)){
$table = '<table>';
if($title){
$table .= '<tr><th colspan="20">'.$title.'</th></tr>';
}
foreach($var as $k => $v){
$table .= '<tr>';
$table .= '<td><b>'.$k.'</b></td>';
$table .= '<td>';
if(is_array($v)){
$table .= nicevar($v);
}else{
$table .= $v;
}
$table .= '</td>';
$table .= '</tr>';
}
$table .= '</table>';
}else{
$table = $var;
}
return $table;
}
usage:
echo nicevar($_SESSION['debug'],'Structure of debug');
use this styling to make it nice:
<style>
body {
padding: 30px;
}
table {
margin: 5px;
}
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th {
background-color: #9fff96;
}
th, td {
padding: 2px;
border-spacing: 2px;
}
</style>
in CI4, it's simpler to make the output prettier:
dd($this->request);
here is the result
I wrote a function (debug_display) which can print, arrays, objects, and file info in pretty way.
<?php
function debug_display($var,$show = false) {
if($show) { $dis = 'block'; }else { $dis = 'none'; }
ob_start();
echo '<div style="display:'.$dis.';text-align:left; direction:ltr;"><b>Idea Debug Method : </b>
<pre>';
if(is_bool($var)) {
echo $var === TRUE ? 'Boolean(TRUE)' : 'Boolean(FALSE)';
}else {
if(FALSE == empty($var) && $var !== NULL && $var != '0') {
if(is_array($var)) {
echo "Number of Indexes: " . count($var) . "\n";
print_r($var);
} elseif(is_object($var)) {
print_r($var);
} elseif(#is_file($var)){
$stat = stat($var);
$perm = substr(sprintf('%o',$stat['mode']), -4);
$accesstime = gmdate('Y/m/d H:i:s', $stat['atime']);
$modification = gmdate('Y/m/d H:i:s', $stat['mtime']);
$change = gmdate('Y/m/d H:i:s', $stat['ctime']);
echo "
file path : $var
file size : {$stat['size']} Byte
device number : {$stat['dev']}
permission : {$perm}
last access time was : {$accesstime}
last modified time was : {$modification}
last change time was : {$change}
";
}elseif(is_string($var)) {
print_r(htmlentities(str_replace("\t", ' ', $var)));
} else {
print_r($var);
}
}else {
echo 'Undefined';
}
}
echo '</pre>
</div>';
$output = ob_get_contents();
ob_end_clean();
echo $output;
unset($output);
}
Use
echo nl2br(var_dump());
This should work ^^
I am working on some PHP classes that can do some basic profiling, debugging, and error handling. Yes I know about XDebug and it's great, but I would like to have some classes as well for my library to do some of this type of stuff.
Below is a class I am working on that will show an error message when one occurs and will show me the line number it happened on as well as the source code for that line and the X amount of lines below and above the error line. Similar to in this image below... (may have to view image in new window/tab to see larger version)
Here is my class code I have as of right now for this...
<?php
class Debugger
{
public static function debug_source($file, $line_number, $padding = 5)
{
if (!$file or !is_readable($file)) {
return false;
}
// Open the file and set the line position
$file = fopen($file, 'r');
$line = 0;
// Set the reading range
$range = array('start' => $line_number - $padding, 'end' => $line_number + $padding);
// Set the zero-padding amount for line numbers
$format = '% ' . strlen($range['end']) . 'd';
$source = '';
while (($row = fgets($file)) !== false)
{
// Increment the line number
if (++$line > $range['end'])
break;
if ($line >= $range['start']){
// Make the row safe for output
$row = htmlspecialchars($row, ENT_NOQUOTES);
// Trim whitespace and sanitize the row
$row = '<span class="number">' . sprintf($format, $line) . '</span> ' . $row;
if ($line === $line_number){
// Apply highlighting to this row
$row = '<span class="line highlight">' . $row . '</span>';
} else{
$row = '<span class="line">' . $row . '</span>';
}
// Add to the captured source
$source .= $row;
}
}
// Close the file
fclose($file);
echo '<div id="exception_error">';
echo ' <h1><span class="type"> Error [ 345 ]</span></h1>';
echo ' <div class="content">';
echo ' <p>Test error message on line number ' . $line_number. '</p>';
echo ' <p><pre class="source"><code>' . $source . '</code></pre></p>';
echo ' </div>';
echo '</div>';
}
}
// Testing the class above.
$file = 'bitmask/bitmasktest.php';
$line_number = 82;
$line_number_padding = 5;
$debugger = new Debugger();
$debugger->debug_source($file, $line_number, $line_number_padding);
?>
So I am looking for ways to improve and add on to this. It is not complete yet, this is just a start.
A couple of basic questions.
1) Should I declare all variables in a class like this at the top? For example in this class I access the properties like this $file, $line_number, $padding. Should I declare them at the top (all properties) like...
<?php
//public/private/protected
public $this->file;
private $this->$line_number;
private $this->padding;
// etc, etc, for every single property used in a class method
// or should I access them how I currently do in
// this class like $file, $line_number, etcc????
?>
?>
2) To make the output look correct from my method above, it needs this CSS data below in the page, I know I should probably include a CSS file for it or add it to my other css files, but my goal is to have this class be self contained, so the class can be ran anywhere and have the correct output. Should I somehow have a method that outputs the CSS needed for this class or what are some good ideas to keep it self contained and still look the way I want it (like in the image)?
<style type="text/css">
#exception_error {
background: #ddd;
font-size: 1em;
font-family:sans-serif;
text-align: left;
color: #333333;
}
#exception_error h1,
#exception_error h2 {
margin: 0;
padding: 1em;
font-size: 1em;
font-weight: normal;
background: #911911;
color: #FFFFFF;
}
#exception_error h1 a,
#exception_error h2 a {
color: #FFFFFF;
}
#exception_error h2 {
background: #666666;
}
#exception_error h3 {
margin: 0;
padding: 0.4em 0 0;
font-size: 1em;
font-weight: normal;
}
#exception_error p {
margin: 0;
padding: .4em;
}
#exception_error a {
color: #1b323b;
}
#exception_error p {
margin: 0;
padding: 0.1em 0;
}
#exception_error pre.source {
margin: 0 0 1em;
padding: 0.4em;
background: #fff;
border: dotted 1px #b7c680;
line-height: 1.2em;
}
#exception_error pre.source span.line {
display: block;
}
#exception_error pre.source span.highlight {
background: #f0eb96;
}
#exception_error pre.source span.line span.number {
color: #666;
}
</style>
<style type="text/css">
.linenum{
text-align:right;
background:#FDECE1;
border:1px solid #cc6666;
padding:0px 1px 0px 1px;
font-family:Courier New, Courier;
float:left;
width:17px;
margin:3px 0px 30px 0px;
}
code {/* safari/konq hack */
font-family:Courier New, Courier;
}
.linetext{
width:700px;
text-align:left;
background:white;
border:1px solid #cc6666;
border-left:0px;
padding:0px 1px 0px 8px;
font-family:Courier New, Courier;
float:left;
margin:3px 0px 30px 0px;
}
br.clear {
clear:both;
}
</style>
Thank you for any help, I realize these are some really newby like questions but I do need some help, I don't want to pick up any bad habits.
First: the way to declare class properties is like this:
class Debugger {
public $file;
private $line_number;
private $padding;
}
Now, class properties only make sense if they remain constant between operations (function calls) performed on the same object -- in other words, if their values can be "reused" between calls. In your case, the only one of these which it makes sense to reuse is $padding (set it once and then call debug_source multiple times with the same padding). The other two should remain function parameters.
Second:
There is absolutely no way you can make Debugger be self-container and have it produce valid HTML in the context of your page at the same time, unless you make all those styles inline. Of course this solution is far from optimal, but it's the only one that you can use in this case.
1) No. Property declaration does not include the $this keyword. You only use that when accessing the properties, eg
class Foo
{
private $foo;
private $bar;
public function __construct($foo, $bar)
{
$this->foo = $foo;
$this->bar = $bar;
}
}
2) In this case, I'd be more inclined to include all the relevant style attributes in your generated markup. Then it will be truly stand-alone and is how XDebug formats its debug messages.
I'm trying to create a variable background, where the image changes based on the time of day. This code I have USED to work, but I did something somewhere along the line and didn't notice that the functionality had broken. Can someone explain to me why this doesn't work?
<html>
<?php
function day()
{
if ( $hour >= 6 && $hour <= 18 )
{
return 1;
} else { return 0; }
}
?>
<style type="text/css">
body
{
background-image: url('<?php echo (day() ? 'images/day_sheep.jpg'
: 'images/night_sheep.jpg'); ?>');
background-position: 50% 50%;
background-repeat: no-repeat;
background-color: silver
}
a {text-decoration:none;}
a:link {color:#ff0000;}
a:visited {color:#0000FF;}
a:hover {text-decoration:underline;}
</style>
</html>
Inside your function day(), $hour is unset. It will be treated as 0 in a numerical context, and if you enable reporting of notices, you will see notices warning you of an unset variable. Did it used to be a global variable? Did you remove code that set its value or declared it as global?
Edit: Also, on a point of style, I feel it would look neater to have an external CSS file like this:
body {
background-position: 50% 50%;
background-repeat: no-repeat;
background-color: silver
}
body.day {
background-image: url('images/day_sheep.jpg');
}
body.night {
background-image: url('images/night_sheep.jpg');
}
and then you can get rid of the CSS section of your php script, but include the above CSS file, and you need only have the following:
<body class="<?php echo day() ? 'day' : 'night'; ?>">
You never declare what $hour is.
<html>
<?php
function day()
{
$hour = date('G');
if ( $hour >= 6 && $hour <= 18 )
{
return 1;
} else { return 0; }
}
?>
... snip ...