Menu
  • HOME
  • TAGS

How do I set main URL a priority of 1.0 and subdirectory urls priority of 0.5 in sitemap.xml

Tag: php,xml,sitemap,priority,sitemap.xml

How can I make the root index in the sitemap a priority of 1.0 and the rest of the sub directory files a priority of 0.5?

I'm using this php code to generate my sitemap on the fly when page is accessed.

As it is right now, it gives a priority of whatever the set value is

$url -> appendChild( $priority = $xml->createElement('priority', '0.5') );

for every url in the sitemap like in this example:

sitemap example

PHP code that creates sitemap:

<?
$ignore = array( 'images', 'css', 'includes', 'cgi-bin', 'xml-sitemap.php' );

  function getFileList($dir, $recurse=false) {
  global $ignore;

    $retval = array();

    // open pointer to directory and read list of files
    $d = @dir($dir) or die("getFileList: Failed opening directory $dir for reading");
    while ( false !== ( $entry = $d->read() ) ) {

        // Check if this dir needs to be ignored, if so, skip it.
        if ( in_array( utf8_encode( $entry ), $ignore ) )
            continue;

      // skip hidden files
      if($entry[0] == ".") continue;
      if(is_dir("$dir$entry")) {
        $retval[] = array(
          "name" => "$dir$entry/",
          "type" => filetype("$dir$entry"),
          "size" => 0,
          "lastmod" => filemtime("$dir$entry")
        );
        if($recurse && is_readable("$dir$entry/")) {
          $retval = array_merge($retval, getFileList("$dir$entry/", true));
        }
      } elseif(is_readable("$dir$entry")) {
        $retval[] = array(
          "name" => str_replace('./','/', $dir),
          "type" => mime_content_type("$dir$entry"),
          "size" => filesize("$dir$entry"),
          "lastmod" => filemtime("$dir$entry")
        );
      }
    }
    $d->close();

    return $retval;
  }

  $dirlist = getFileList("./", true);  

    // sitemap creation
    $time  = time();
    $sitemap = $_SERVER['DOCUMENT_ROOT'].'/sitemap.xml';
    if ($time - filemtime($sitemap) >= 1) { // 1 days

        $xml = new DomDocument('1.0', 'utf-8'); 
        $xml->formatOutput = true; 

        // creating base node
        $urlset = $xml->createElement('urlset'); 
        $urlset -> appendChild(
            new DomAttr('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9')
        );

            // appending it to document
        $xml -> appendChild($urlset);

        // building the xml document with your website content
        foreach($dirlist as $file)
        {
        if($file['type'] != 'text/x-php') continue;
            //Creating single url node
            $url = $xml->createElement('url'); 

            //Filling node with entry info
            $url -> appendChild( $xml->createElement('loc', 'http://www.airsahara.in'.$file['name']) ); 
            $url -> appendChild( $lastmod = $xml->createElement('lastmod', date('Y-m-d', $file['lastmod'])) ); 
            $url -> appendChild( $changefreq = $xml->createElement('changefreq', 'monthly') ); 
            $url -> appendChild( $priority = $xml->createElement('priority', '0.5') ); 

            // append url to urlset node
            $urlset -> appendChild($url);

        }
        $xml->save($sitemap);
    } // if time



    ?>

Best How To :

I'm answering my own question because I figured it out.

I simply did this. I took this line of code and expanded it with an if and else statement.

went from this

$url -> appendChild( $priority = $xml->createElement('priority', '0.5') );

to this

    if($file['name'] != '/') {
    $url -> appendChild( $priority = $xml->createElement('priority', '0.5') );
    } else {
        $url -> appendChild( $priority = $xml->createElement('priority', '1.0') );
    }

Update: As per the comments of hakre

        if ($file['name'] != '/') {
            $p = '0.5';
            } else {
                $p = '1.0';
            }
        $url -> appendChild( $priority = $xml->createElement('priority', $p) );

And this would be the shorthand of the if else statement

        $file['name'] != '/' ? $p = '0.5' : $p = '1.0';
        $url -> appendChild( $priority = $xml->createElement('priority', $p) );

XSLT How to remove style from div and td tags

xml,xslt

To remove some nodes start with the identity transformation template <xsl:template match="@* | node()"> <xsl:copy> <xsl:apply-templates select="@* | node()"/> </xsl:copy> </xsl:template> then add an empty template for the nodes to be removed: <xsl:template xmlns:xhtml="http://www.w3.org/1999/xhtml" match="xhtml:div/@style | xhtml:li/@style | xhtml:td/@style | xhtml:span/@style"/> ...

Collect strings after a foreach loop

c#,xml,foreach

Yep, you need to do the adding within the loop. I'd use a List<string> as it supports LINQ: XmlNodeList skillNameNodeList=SkillXML.GetElementsByTagName("name"); List<string> skills = new List<string>(); foreach (XmlNode skillNameNode in skillNameNodeList) { skills.Add(skillNameNode.Attributes["value"].Value); } ...

Laravel Interfaces

php,laravel,interface,namespaces

In my recent laravel 5 project, I'm used to prepare my logics as Repository method. So here's my current directory structure. For example we have 'Car'. So first I just create directory call it libs under app directory and loaded it to composer.json "autoload": { "classmap": [ "database", "app/libs" //this...

C# XML: System.InvalidOperationException

c#,xml

Is "User Info" and "Course Data" is a different entity. If it is so, I think you may encapsulate them in one entity. XmlTextWriter writer = new XmlTextWriter(path, System.Text.Encoding.UTF8); writer.WriteStartDocument(true); writer.Formatting = Formatting.Indented; writer.Indentation = 4; writer.WriteStartElement("My Entity"); /* It is a biggest one*/ writer.WriteStartElement("User Info"); writer.WriteStartElement("Name"); writer.WriteString(userName); writer.WriteEndElement(); writer.WriteStartElement("Tutor...

Time format conversion with PHP

php,time

<?php $duration="1H10M5S"; $display=str_replace(array('H','M','S'), array(' Hour(s) ',' Minute(s) ',' Seconds'), $duration); echo $display; Output 1 Hour(s) 10 Minute(s) 5 Seconds Fiddle...

Convert contents of an XmlNodeList to a new XmlDocument without looping

c#,xml,xpath,xmldocument,xmlnodelist

If you're happy to convert it into LINQ to XML, it's really simple: XDocument original = ...; // However you load the original document // Separated out for clarity - could be inlined, of course string xpath = "//Person[not(PersonID = following::Person/PersonID)]" XDocument people = new XDocument( new XElement("Persons", original.XPathSelectElements(xpath) )...

How to Match a string with the format: “20959WC-01” in php?

php,regex

$pattern = '! ^ # start of string \d{5} # five digits [[:alpha:]]{2} # followed by two letters - # followed by a dash \d{2} # followed by two digits $ # end of string !x'; $matches = preg_match($pattern, $input); ...

How to pass a value from a page to another page in PHP

php

Only values that are sent by a form will be in the GET or POST array. From what you are showing I conclude that you don't want to show the field in your form, so make it hidden. Add this inside your form tag: <input name="price" type="hidden" value="'.$price.'" class="inputClass"> Also,...

Parsing XML array using Jquery

javascript,jquery,xml,jquery-mobile

EMI and CustomerName are elements under json so you can use .find() to find those elements and then text() to get its value. $(data).find("json").each(function (i, item) { var heures = $(item).find("CustomerName").text(); var nbr = $(item).find("EMI").text(); console.log(heures); }); .attr() is used to get the attribute value of an element like in...

What are correct permissions for Linux Apache2 PHP 5.3 log file?

php,linux,apache,logging,permissions

I'd simply set its owner to apache user. This will give you the name of apache user : ps aux | grep httpd In my case (CentOS), it's 'apache' but sometimes it's 'www-data'... chown apache:apache /var/log/httpd/php_errors.log chmod 600 /var/log/httpd/php_errors.log ...

mysql_real_escape_string creates \ in server only not in local

php,sql

Your server has magic quotes enabled and your local server not. Remove it with the following sentence set_magic_quotes_runtime(0) As this function is deprecated and it will be deleted in PHP 7.0, I recommend you to change your php.ini with the following sentencies: magic_quotes_gpc = Off magic_quotes_runtime = Off If you...

Fixed element in android?

android,xml,android-fragments

You need a FrameLayout. In a FrameLayout, the children are overlapped on top of each other with the last child being at the topmost. activity_main.xml <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:fab="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent"...

Trying to rewrite mysql_* to pdo

php,mysql,pdo

I don't know the source of the array $arr = array();, but it is assigned to null before the insert query. So it means, literally you are inserting nothing into the database. So check your array well, maybe it was to be like $arr = array('name'=>'My Name', 'url'=>'url', 'email'=>'my email',...

Include both local and server at the same time

php

file_exists: http://php.net/manual/en/function.file-exists.php is_dir: http://php.net/manual/en/function.is-dir.php Best way to do that is use dirname(__FILE__) which gets the directory's full path of the current file in ether unix of windows format. Then we use realpath() which conveniently returns false if file does not exist. All you have to do is specify a relative...

Mixing

php

Set short_open_tag=On in php.ini And restart your Apache server...

$http.get returns actual php script instead of running it (yeoman, grunt)

php,angularjs,pdo,gruntjs

Change $http.get('/scripts/php/articles.php') to $http.get('http://YOURDOMAIN.COM/scripts/php/articles.php') Off course you need to replace YOURDOMAIN.COM with localhost or any other domain you are using....

Pull information from SQL database and getting login errors

php,sql,database

change $username = "'rylshiel_order"; to $username = "rylshiel_order"; and you should be through. You are passing on an extra single quote here. ...

Symfony 2 unable to pass entity repository to form

php,forms,symfony2,runtime-error

You have not included the Symfony EnityRepository class at the top of your form file so PHP is looking for it in the same directory as your form class. Hence the error message. Add this to your form class (or qualify EntityRepository inline): use Doctrine\ORM\EntityRepository; ...

PHP / MySQLi: How to prevent SQL injection on INSERT (code partially working)

php,mysql,mysqli,sql-injection,sql-insert

In the New PHP code snippet, you are still vulnerable to injections. You are using a prepared statement in the insert part, but you are not actually using the preparations strengths correctly. When creating a prepared statement, you create a query in which you add placeholders instead of the raw...

How do I display my mysql table column headers in my php/html output?

php,html,mysql,table,data

Note: You can just make a single file out of it to achieve your wanted output Use mysql_real_escape_string() to sanitize the passed-on value to prevent SQL injections You should use mysqli_* instead of the deprecated mysql_* API Form them in a single file like this (display.php): <html> <form method="post" name="display"...

How to secure configuration file containing database username and password

php,security

As @Darkbee stated, the simplest way is to have the file outside your website root. This would be accessible on the server, but not to the public under any circumstances. The alternative is to set the permissions to 400 on the file. .htaccess could block access, but not blocking access...

access the json encoded object returned by php in jquery

php,jquery,ajax,json

Try: $.ajax({ url: "functions.php", dataType: "JSON", data: {id: id}, type: 'POST', success: function(json){ for(var i=0;i<json.length;i++){ alert(json[i].fname); } } }); ...

php include capitalization on files

php

Your local host must be Windows, that doesn't differentiate between upper and lower case in file names and your web server Unix Based which does, simple as that.

How can I replace the white rectangle within an image using ImageMagick?

php,image-processing,imagemagick

I think you can locate the shape pretty accurately with a simple threshold, like this: convert image.jpg -threshold 90% result.jpg and you can then do a Canny edge detection like this: convert image.jpg -threshold 90% -canny 0x1+10%+30% result.jpg The next things I would be looking at are, using the -trim...

Cant submit form

javascript,php

Your PHP is checking if $_POST['submit'] contains a value. Your form does not contain a form element with the attribute name="submit", so therefore it fails and moves straight to the else statement. If you want to check if the form was posted then you should instead check for: if (!empty($_POST))...

PHP Regular Expressions Counting starting consonants in a string

php,regex

This is one way to do it, using preg_match: $string ="SomeStringExample"; preg_match('/^[b-df-hj-np-tv-z]*/i', $string, $matches); $count = strlen($matches[0]); The regular expression matches zero or more (*) case-insensitive (/i) consonants [b-df-hj-np-tv-z] at the beginning (^) of the string and stores the matched content in the $matches array. Then it's just a matter...

Laravel 4.2 Sending email error

php,email,laravel,laravel-4

Closures work just like a regular function. You need to inject your outer scope variables into function's scope. Mail::send('invoices.mail', array($pinvoices,$unpinvoices), function($message) use ($email) { $message->to($email , 'Name')->subject('your invoices '); }); ...

Error when building an XDocument

c#,xml,linq,xpath,linq-to-xml

You can ignore pretty much all your code, the issue is just this: XDocument people = new XDocument("Persons"); You can't create an XDocument containing a string, you need to add an element: XDocument people = new XDocument( new XElement("Persons", original.XPathSelectElements(xpathFilterDups))); ...

Click on link next link should be display on same page

javascript,php,jquery,html,css3

Ok, so i tried to decypher what you meant with your Question. To Clarify: He has this one page setup. inside the div Our Project, there are two Buttons or links Visit more. When clicked, he wants the About Section to be shown. All in all it is impossible for...

RecursiveIteratorIterator to fetch subdirectories

php

I would change if ( $dir->isDir() ) to if ( $dir->isDir() && $dir != $root) to remove the root directory...

Php Mysql Query not working properly

php,mysql

No need to use union as it will give a lots of duplicate data What you want to achieve can be done with simple left join or inner join SELECT m.issue_name ,m.issue_type , m.priority ,m.status,m.description , m.start_date,m.end_date,m.duration, s.name as server_name,p.name as product_name from mod_networkstatus as m LEFT JOIN tblservers as...

Load XML to list using LINQ [duplicate]

c#,xml,linq

Make a base class which will have id,x,y,z, and have Vendors,Bankers and Hospitals extend it. Then you can have a collection of the base class, and add to it the classes that inherit from it....

Codeigniter PHP Mailer, Sender Info

php,email,codeigniter-2,phpmailer,contact-form

Don't do that. It's effectively forging the from address and will fail SPF checks. Instead, use your own address as the From address, and add the submitted address as a reply-to address. In PHPMailer: $mail->From = '[email protected]'; $mail->addReplyTo($POST['emailfrom']); ...

Dynamically select from a dynamically generated dropdown

php,html,select,drop-down-menu

It is because you aren't ending the value attribute, so your selected option becomes <option value="optionvalueselected" -- 'optionvalue' being the value of your selected option, and 'selected' being the attribute you want to set, but won't be set because you never ended value The following should work: <select name="course_id" id="course_id">...

array and function php

php,arrays

$x and $y are only defined within the scope of the function. The code outside of the function does not know what $x or $y are and therefore will not print them. Simply declare them outside of the function as well, like so: <?php function sum($x, $y) { $z =...

MySQL Query returning strange values

php,mysql

You need to join by account_id and also question_id SELECT * FROM `quiz_questions` INNER JOIN `quiz_answers` ON `quiz_questions`.`account_id` = `quiz_answers`.`account_id` AND `quiz_questions`.`question_id` = `quiz_answers`.`question_id` WHERE `quiz_questions`.`account_id` = '1840979156127491' ORDER BY `quiz_questions`.`question_id` ASC LIMIT 5 ...

Composer dump-autoload gives preg_match error

php,composer-php,autoload

autoload should be moved out of require-dev: { "require-dev":{ "phpunit/phpunit":"4.5.*" }, "autoload":{ "psr-0":{ "Yii\\":"yii-1.1.14.f0fee9/" } } } You can test your composer.json file using composer validate. Your original file returned: ./composer.json is invalid, the following errors/warnings were found: require-dev.autoload : invalid value, must be a string containing a version constraint...

Wordpress log out using URL and redirect to specify page

javascript,php,wordpress

Try wp_logout() function use the funtion . if($_GET['logout'] == 1) { ob_start(); error_reporting(0); wp_logout(); $redirect = wp_logout_url(); wp_safe_redirect( $redirect ); } ...

Error connecting to MSSQL using PHP

php,sql-server,pdo,odbc,sqlsrv

Change it to: $this->link = new PDO( "sqlsrv:Server={$this->serverName},{$this->port};Database={$this->db};", $this->uid, $this->pwd ); The default SQL Server port is 1433. Note the curly brackets, they allow for class variables....

How to calculate max string-length of a node-set?

xml,xslt,xslt-1.0,libxslt

<xsl:variable name="max_a_width"> <xsl:for-each select="data"> <xsl:sort select="string-length(@a)" data-type="number" /> <xsl:if test="position() = last()"> <xsl:value-of select="string-length(@a)" /> </xsl:if> </xsl:for-each> </xsl:variable> This is the general method of picking from an ordered list of derived values in XSLT 1.0. If you want to pick the minimum/maximum from actual (natively sortable) values, you can take...

php redirection working in chorme but not on firefox

php,google-chrome,mozilla

have you tried using header('location') function? example : <?php if (isset($_POST['putonline'])) { $query = "UPDATE user SET status= '1' WHERE id= '$new_id'"; $result = $cid-> query($query); if ($result== TRUE) { header("location:EidEmp.php"); die(); } else { echo "Failed"; } } ?> Edited : Maybe Change Your header function with javascript function...

Unable to configure Symfony (3rd party) bundle

php,symfony2,rss

I havent tried this bundle yet, but i think you need to tell doctrine that you want to save your newly created feed into the database: $feeds = new Feed; $reader->readFeed($url, $feeds, $date); $em = $this->getDoctrine()->getManager(); $em->persist($feeds); $em->flush(); return $this->render('default/index.html.twig'); UPDATE According to the docs if you want to use...

How to search images by name inside a folder?

php,mysql,image

This looks like a job for glob, which returns an array of file names matching a specified pattern. I'm aware of the other answer just posted, but let's provide an alternative to regex. According to the top comment on the docs page, what you could do is something like this:...

When I click to the next page on pagination,it goes to 404 error in codeigniter

php,codeigniter,pagination

in config.php $config['base_url'] = ''; $config['index_page'] = ''; in your router $route['news/(:any)'] = 'news/$1'; $route['news'] = 'news'; $route['default_controller'] = 'news/create'; $route['(:any)'] ='pages/view/$1'; and place .htaccess <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php/$1 [L] </IfModule> EDIT 01 <?php $data['title'] = 'Database Details'; $count = $this->news_model->record_count()...

How to modify CodeIgniter calendar to handle multiple events per day?

php,codeigniter,calendar

If you want to show all four boxes for the dates which has data, try to change the get_calendar_data() foreach as below, $content = ""; $lastDay = -1; $index = 0; foreach ($query->result() as $row) { if($lastDay != intval(substr($row->date_cal, 8, 2))){ if($index > 0 ){ if($content != ''){ $cal_data[$lastDay] =...

Why am getting this error?: Unknown column 'firstname' in 'field list'

php,database,mysqli

$query = "INSERT INTO `myDatabaseForAll`.`users` (`id`, `firstname`, `lastname`, `username`, `password`) VALUES (NULL, $firstname, $lastname,$username,$password)"; you need single quote around text feilds in sql queries change above query to $query = "INSERT INTO `myDatabaseForAll`.`users` (`id`, `firstname`, `lastname`, `username`, `password`) VALUES (NULL, '$firstname', '$lastname','$username','$password')"; ...

how to escape php code in echo with javascript

javascript,php

You are mixing inline PHP with a PHP command (echo). When you are echoing a string, you do it just like normal, this means you can mix literal strings (the js you are manually typing) and the output of functions (like a json in this case): echo "<script type='text/JavaScript'> var...

How to register global variable for my Laravel application?

php,laravel,laravel-5

Actually, you should reserve in config/app.php file. Then, you can add In the Service Providers array : 'Menu\MenuServiceProvider', In the aliases array : 'Menu' => 'Menu\Menu', Finally, you need to run the following command; php artisan dump-autoload I assume that you already added this package in composer.json Sorry, I didn't...

how to multiply two column names using codeigniter validation rule

php,codeigniter,validation

You done need to do anything with your controller. Add this change your view to <script> function calculate() { var myBox1 = document.getElementById('crop_quantity').value; var myBox2 = document.getElementById('per_rate').value; var result = document.getElementById('income_amount'); var myResult = myBox1 * myBox2; result.value = myResult; } window.onload = calculate(); </script> <div class="control-group"> <label class="control-label">Crop Quantity</label>...

compare today's date with unix timestamp value in database

php,mysql

If I understand correctly you have a unix timestamp in a varchar field and you can't change this. If you compare the unix timestamp directly you will only get results that match the exact second of the timestamp. You can use FROM_UNIXTIME() to convert the timestamp in a date value...