php find xml node thanks to isset variable form url [closed] - xpath

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I have a single.php page where I want to load individual post.
To do this I have some links in my index.php that allows to load single.php page :
Post 12
Post 11
Post 10
I get the variable in the url in my single.php page and I want to find (and display), in a xml file, the element that correspond to this variable:
<?php
if(isset($_GET["blog_no"])) {
$i = $_GET["blog_no"];
$elements = new SimpleXMLElement('data.xml', null, true);
$query = $elements->xpath(" /elements/element[#id='$i'] ");
foreach($query as $element) {
echo $elements->element['size'];
echo $elements->element['category'];
echo $elements->element->title;
}
?>
Here an example of my xml file:
<elements>
<element id="12" size="square" category="portfolio">
<tag tag="printer printing 3d apple iphone 5 bumper case"></tag>
<icon class="icon-picture"></icon>
<urlpage url="/contact/contact.html"></urlpage>
<urlimage src='./Post thumbnail images/01.png'></urlimage>
<date date="8 Apr"></date>
<title>Minimal Bumper for iPhone 5 : Protect your iphone with a lightwheight and protect full case </title>
</element>
<element id="11" size="normal" category="portfolio">
<tag tag="printer printing 3d apple iphone 5 case slim"></tag>
<icon class="icon-picture"></icon>
<urlpage url="/portfolio/11.html"></urlpage>
<urlimage src='./Post thumbnail images/tape-dribbble.jpg'></urlimage>
<date date="21 Jan"></date>
<title>UltraSlim case</title>
</element>
</elements>
But nothing works.

You were quite close to it, do it like this:
if (isset($_GET['blog_no'])) {
$id = $_GET['blog_no'];
$xml = simplexml_load_string($x); // assume XML in $x
$element = $xml->xpath("//element[#id='$id']")[0];
echo "$element[size] - $element[category]<br />$element->title<br />";
} else {
echo "No post selected!"
}
Explanation:
in xpath, //element means to select every <element> at any position in the XML
xpath will always return an array, the [0] will select only the 1st match. This syntax will work in PHP >=5.4, if you're below, let me know and I'll post the right code.
No need for foreach, there can only be one <element> selected, because the id is unique (I guess).
See it working: http://codepad.viper-7.com/LY3itL

I found a solution :
if(isset($_GET["blog_no"])) {
if (file_exists('data.xml')) {
$elements = new SimpleXMLElement('data.xml', null, true);
foreach ($elements->element as $element) {
if ($element['id'] == $_GET["blog_no"]) {
echo $element['size'];
echo $element['category'];
echo $element->title;
break;
}
}
}else {
exit('Failed to open data.xml.');
}
}
I don't know if it's the best way to do it but it works great.

How about this...
<?php
if (isset($_GET['blog_no']))
{
$i = $_GET['blog_no'];
if (file_exists('data.xml'))
{
$xml = simplexml_load_file('data.xml');
$query = '/elements/element[#id="'.$i.'"]';
$elements = $xml->xpath($query);
foreach ($elements as $element)
{
echo $element['size'];
echo $element['category'];
echo $element->title;
}
}
else
{
exit('Failed to open data.xml.');
}
}
?>
See above Xpath working here: codepad.viper-7.com/QgYeqK.
Thanks go to #michi for introducing codepad.viper-7.com.

Related

php/mysql comments duplicating automatically on pages reload

I have created a commenting system for my website. The problem I have is that, the old comments duplicate themselves anytime the webpage is refreshed or reloaded.
How can I stop this and only show original comments?
I have added the entire code here below:
<pre>
require 'data/connect.php';
if(isset($_POST['name'])&& isset($_POST['comment'])){
$name = trim($_POST['name']);
$comment = trim($_POST['comment']);
if(!empty($name) && !empty($comment)){
$insert = $connect->query("INSERT INTO
comments(name,comment)VALUES('$name','$comment')");
if($insert){
echo "Success";
}else{
echo "Sorry";
}
}
}
?>
</pre>
form here
<pre>
<?php
if(isset($_POST['name'])&& isset($_POST['comment'])){
$name = trim($_POST['name']);
$comment = trim($_POST['comment']);
if(!empty($name) && !empty($comment)){
$query = $connect->query("SELECT name,comment FROM comments WHERE name='$name' AND comment='$comment'");
while($row = $query->fetch_object()){
echo "<b>",$row->name,"</b><br/>",$row->comment;
}
}
}
?>
</pre>
Your help will be appreciated.
Send out a unique value (created with php's uniqid() for example) in a hidden field in the form. Every time you send the form to a browser, change the value. If you get the same value twice from the same browser, you know it was a double post.
You could also compute a hash of the posted information and compare that against hashes of what's already in the database, for speed, you could store the hash for each comment in the database.
You may also be able to restrict this at the database level, for example by using replace instead of insert (for mySQL).

CodeIgniter : image upload on article

I'm building a website with MongoDB and Codeigniter where users can create articles (title + text) and after it (but before to submit), upload some pictures (images are not in the text).
I think i will use jquery.upload for it. But my question is how to do link between pictures and article (because img will be uploaded first), how to rename them ?, is there any good way to do this ?
jquery upload would work. and check if it is success then create new hidden input into the form and set its value as you wish to use.
While I've never attempted this feature, this is a hypothetical solution that popped in my head:
Create a unique string on your Create Article page, and insert it into your document as a hidden field. A random string of 6 characters or something would probably be sufficient.
When uploading the images, use that string as an identifier for what future post the images belong to. Use the string in the file name, path, DB entry, or whatever's useful for your scenario.
When the article itself is submitted, the unique string will allow it to be identified with the images, and you can work whatever magic you need to at that stage to fully commit everything together.
Keep in mind that you should have some sort of statistics and/or garbage collection regarding any images that are uploaded and then the related article is abandoned.
Add 'thumbnail' field in your table 'articles_table' . I removed the unnessary parts for simpler need.We will only use 'title' and 'thumbnail' as field.
View | create.php
<?php echo form_open_multipart('articles/insert'); ?>
Title <br>
<?php echo form_input('title','','id="title_input"'); ?><br>
Thumbnail<br>
<input type="file" name="file" size="20" />
<?php echo form_submit('Submit',"Submit"); ?>
<?php echo form_close(); ?>
Controller | articles.php
function insert()
{
//$this->articles_model->insert();
$this->articles_model->save();
redirect('articles/index');
}
Model | articles_model.php
function save($id=0)
{
$title=$this->input->post('title');
//Set the config
$config['upload_path'] = './files/';
$config['allowed_types'] = 'gif|jpg|png|PNG';
$config['max_size'] = '1100';
$config['max_width'] = '11024';
$config['max_height'] = '1768';
$config['overwrite'] = FALSE;
//Initialize
$this->upload->initialize($config);
//Upload file
if( ! $this->upload->do_upload("file"))
{
//echo the errors
echo $this->upload->display_errors();
}
//If the upload success
$thumbnail = $this->upload->file_name;
if($id<1)
{
$data=array(
'title'=>$title,
'thumbnail'=>$thumbnail
);
$this->db->insert('articles_table',$data);
}
}

How to render banners alongside featured items in home page

I'm making a custom template form joomla 2.5, and one of the goals for the development is to include a banner after each featured article iteration.
After a long research I can render a banner into /template_name/html/com_content/featured/default_item.php with the following code:
$document = JFactory::getDocument();
$renderer = $document->loadRenderer('modules');
$position = "nota";
$options = array('style' => 'raw');
echo $renderer->render($position, $options, null);
But the issue is that each iteration resets the banner list so I have the same banner repeated with each featured article.
I tried to include the banner module using the same code in /template_name/html/com_content/featured/default.php without success. Lately I'd try with <jdoc:include type="modules" name="nota" style="raw" /> and it didn't works too, so I will appreciate any help to solve this point.
Thanks in advance.
You can solve this in two ways.
The right way
Copy and rename the banner module (fx. to mybanners), change the getList() method in the helper file to retrieve different banners on each call. This could fx. be:
class modMybannersHelper
{
static function &getList(&$params)
{
static $index = 0;
JModelLegacy::addIncludePath(JPATH_ROOT.'/components/com_banners/models', 'BannersModel');
$document = JFactory::getDocument();
$app = JFactory::getApplication();
$keywords = explode(',', $document->getMetaData('keywords'));
$model = JModelLegacy::getInstance('Banners', 'BannersModel', array('ignore_request'=>true));
$model->setState('filter.client_id', (int) $params->get('cid'));
$model->setState('filter.category_id', $params->get('catid', array()));
$model->setState('list.limit', 1);
$model->setState('list.start', $index++);
$model->setState('filter.ordering', $params->get('ordering'));
$model->setState('filter.tag_search', $params->get('tag_search'));
$model->setState('filter.keywords', $keywords);
$model->setState('filter.language', $app->getLanguageFilter());
$banners = $model->getItems();
$model->impress();
return $banners;
}
}
This is just a sketch; you still need to handle the case of $index being greater than the number of records.
The hacky way
The retrieval code has only one port open to inject conditions - the documents's keywords.
So you could (in your template file) store the original keywords an replace them with a keyword to identify a banner. The banner must have the same keyword in that case.
$document = JFactory::getDocument();
$keywords = $document->getMetaData('keywords');
$renderer = $document->loadRenderer('modules');
$position = "nota";
$options = array('style' => 'raw');
$document->setMetaData('keywords', 'banner_key');
echo $renderer->render($position, $options, null);
$document->setMetaData('keywords', $keywords);
Either way, caching may prevent that from work, so you might have to turn it off (I didn't check that).

Magento, show image on custom frontend block

I've a module up and running. On the backend side I can upload images with several attributes and I'm saving image path and other information on a custom table. On frontend I already managed to detect when I need to show these images. I've used an Observer that adds a new layout handle when the displayed product is found on the custom created table. Then on that layout handle I call a phtml template file and from here I call a function inside a block that will be in charge of doing all the checks to be sure wich image to show.
My problem is that I can not find how to show these images. Everything I found references how to add image tag on a phtml file doing some extra verifications on the inserted php code. Buy on my case everything is on php code outside any phtml file.
My phtml file code:
<div>
<h3><?php $this->showCampaign(); ?></h3>
</div>
My block code for now:
<?php
class Dts_Banners_Block_Front extends Mage_Core_Block_Template {
/**
* Shows a campaign banner according to the current selected product
* Seeks on main banners table to see if it is an image/html/product alone campaign
* Once knows the campaign type search on needed table the needed fields
*/
public function showCampaign() {
//Zend_Debug::dump($this->getLayout()->getUpdate()->getHandles());
$product = Mage::registry('current_product');
$currentProdID = $product->getId();
if (Mage::registry('campaign_data') && Mage::registry('campaign_data')->getId()) {
$currentCampaign = Mage::registry('campaign_data');
} else {
return;
}
// get campaign type and show needed information
switch ($currentCampaign->getbanner_type()) {
case 1: // image
$myImgCollection = Mage::getModel('banners/bannersimg')->getCollection();
$myImgCollection->addfieldtofilter('bannerid',$currentCampaign->getID());
$currentImg = $myImgCollection->getFirstItem();
$currentImgPath = $currentImg->getimg_path();
//{{block type="catalog/product_new" product_id="16" template="catalog/product/view/your_new_page.phtml"}}
break;
case 2: // html
echo "html";
break;
case 3: // plain product url
echo "plain product url";
break;
}
}
}
As usual, couple of hours searching for an answer and when I post the question, found the answer. Just in case someone needs it: is as easy as creating an image html tag inside the code and return it to the template file. Sample code:
<?php
class Dts_Banners_Block_Front extends Mage_Core_Block_Template {
public function showCampaign() {
...
$currentImgPath = $currentImg->getimg_path();
//build html to output to the template
$html .= "<div class=\"visual\">";
$html .= "<img src=\"" . $currentImgPath . "\" alt=\"\" />";
$html .= "</div>";
....
return $html;
}
And the phtml file code:
<div class="visual">
<?php echo $this->showCampaign(); ?>
</div>

Determining which section is being viewed

Folks, I am trying to implement a rudimentary feature in Joomla but having no luck getting my head around it.
My client has setup Joomla with several sections; each section having its own categories and eventually content underneath.
I need each section to have a slightly different color component (e.g. Section A and its all subsequent child pages red, Section B - blue, etc); certain borders and backgrounds need to be unique according to each section.
I have one theme which is used by all sections. Somewhere in the theme file, I need to detect which section I am on, and based on that set a css variable accordingly:
<html>
<body class="cars-section">
</body>
</html>
All I need is to set my body's class to the right section, and all my coloring has been setup to work magically.
Any ideas how this can be done in the Joomla world? Is there another way of doing such a thing.
You need to pick the section ID up from the request.
Use this to get the relevant request variables:
<?php
$option = JRequest::getWord('option', null);
$view = JRequest::getWord('view', null);
$idalias = JRequest::getVar('id', null);
if (strpos($idalias, ":") != false) {
$idandalias = explode(":", $idalias);
$id = $idandalias[0];
} else {
$id = JRequest::getInt ('id' , 0);
}
Then use something like this to see what section you are in, if you are on a section page:
if ( $option=="com_content" && $view=="section" ) {
$sectid = $id;
}
In section pages you can just use the request, but in other pages you need to do a database query as well:
else {
$database =& JFactory::getDBO();
if ( $option=="com_content" && $view=="category" ) {
$query = "SELECT section FROM jos_categories WHERE id=$id";
}
if ( $option=="com_content" && $view=="article" } {
$query = "SELECT sectionid FROM jos_content WHERE id=$id";
}
$database->setQuery($query);
$sectid = $database->loadResult();
}
When you have the section ID you can use it to set and insert the right class.
if ( $sectid == '3' ) {
$my_cars_section_class = 'three';
}
?>
<body class="<?php echo $my_cars_section_class; ?>">
Something like that should do it.
There are a couple of ways to achieve body css-classing:
Utilize Joomla's menu page class suffix system.
Output the class based on the selected menu link from within the template. Of course, if you plan to do this, you'll need to modify your template a bit.
$menu = &JSite::getMenu();
$active = $menu->getActive();
<body <?php if($active->alias) echo 'class="' .$active->alias .'"' ?>>

Resources