how to get data mysql from post view to controller | Codeigniter 3 - php

This is part of function controller:
public function generate_google_post()
{
$query = $this->sitemap_model->get_all_products();
foreach ($query as $row) {
$xml .= '<item>
<g:id>'.$row['id'].'</g:id>
</item>';
}
echo $xml;
}
From view.php In above function I can submit to controller and generate correct XML file with data from mysql.
Issue start from here:
now I want do some customization to write xml content directly in storefront (view) and then call input data to controller and generate xml.
For this I try:
public function generate_google_post2()
{
$xml = '<channel>';
$query = $this->sitemap_model->get_all_products();
foreach ($query as $row) {
$xml .= $this->input->post('add-list');
}
$xml .= '</channel>';
header('Content-type: text/xml');
header('Content-Disposition: attachment; filename="file.xml"');
echo $xml;
}
}
and in view page I try:
<?php echo form_open('sitemap_controller/generate_google_post2'); ?>
<textarea name="add-list" id="add-list" rows="10" cols="75"> </textarea>
<button type="submit" name="process" value="generate" class="btn btn-primary pull-right" style="margin-bottom: 5px;"><?php echo trans('download_feed'); ?></button>
<?php echo form_close(); ?><!-- form end -->
and now in storefront text area form I try post:
<item>
<gid>'.$row['id'].'</gid>
</item>
XML file generate sucess but the problem is I get output XML:
<channel> <item>
<gid>'.$row['id'].'</gid>
</item> <item>
<gid>'.$row['id'].'</gid>
</item> </channel>
So missing data from mysql. Is any way post from text are and in this way get data from database and then generate to xml ?
text area view post
I try add if($_POST) then $query = $this->sitemap_model->get_all_products(); and
foreach ($query as $row) {
$xml .= $this->input->post('add-list');
}
But this not resolved this issue. Full code:
public function generate_google_post2()
{
if($_POST){
$id = $this->input->post('add-list');
$query = $this->sitemap_model->get_all_products();
$xml = '<channel>';
foreach ($query as $row) {
$xml .= $this->input->post('add-list');
}
$xml .= '</channel>';
header('Content-type: text/xml');
header('Content-Disposition: attachment; filename="file.xml"');
echo $xml;
}
}

The $row variable is being interpreted as text. You wouldn't want to do this anyway as you would be very vulnerable to malicious code submitted in the form. Essentially you are trying to provide some template to the backend to fill with data.
Provide a placeholder in your form.
<item><gid>{id}</gid></item>
In your foreach loop, replace the placeholder with your data.
$template = $this->input->post('add-list');
// Replace your placeholder
$template = str_replace('{id}', $row['id'], $template);
$template = str_replace('{title}', $row['title'], $template);
$template = str_replace('{sku}', $row['sku'], $template);
$template = str_replace('{somethingelse}', $row['thing'], $template);
$xml .= $template;
Anyone who uses this form who is not you would need to be instructed what specific text to use as the placeholder. So you would need to know, or control, what placeholders the user enters.
You could control the placeholders on the front end with buttons that insert the text on the cursor. https://jsfiddle.net/xhgk8cz7/1/

Related

how to give line breaks in xml file using php?

I am display mysql data in xml file using php.
there I used this one in here i want to give line breaks .if we give line breaks that will display line break tag in content ..we have to give html tags .but we dont show them in xml content ...
the output is coming like this..
At the same time I want to remove that empty p tags also ...that is.
<![CDATA[ <p> </p>]]>
this is the code i have written for xml ...
please solve this problems
header("Content-Type: application/xml; charset=utf-8");
date_default_timezone_set("Asia/Calcutta");
$this->view->data=$this->CallModel('posts')- >GalleryAndContent();
$xml = '
';
$xml.='Thehansindia
http://www.thehansindia.com
Newspaper with a difference';
foreach($this->view->data as $values)
{
$output=strip_tags($values['text_data'],"");
$output = preg_replace('/(<[^>]+) style=".?"/i', '$1',$output);
$output = preg_replace('/(<[^>]+) class=".?"/i', '$1', $output);
$output=preg_replace( '/style=(["\'])[^\1]?\1/i', '', $output, -1 );
$output=preg_replace("/<([a-z][a-z0-9])[^>]*?(/?)>/i",'',$output);
$output=str_replace(array("",""),array("",""),$output);
$output=str_replace(array("",""),array("",""),,$output);
//$xml.="<CONTENT>"."<![CDATA[".$output."]]>"."</CONTENT>
$xml.= '<item>';
$dom = new DOMDocument;
#$dom->loadHTML($output);
$xml.="<CONTENT>";
foreach ($dom->getElementsByTagName('p') as $tag){
//$tag->nodeValue=str_replace("<![CDATA[ <p> </p> ]]>","",$tag->nodeValue);
if(!empty($tag->nodeValue)){
//$tag->nodeValue=str_replace("<![CDATA[ <p>& & &</p> ]]>","",$tag->nodeValue);
$xml.="<![CDATA["."<p>".stripslashes($tag->nodeValue)."</p>"."]]>";
}
}
$xml.="</CONTENT>";
$xml.= ' </item>';
}
Example:
//Next replace all new lines with the unicode:
$xml = str_replace("\n","
", $xml);
Reference Link

rss feed not displaying

I'm trying to create a rss feed that displays all my news.
So far the code seems to be half way there because if I view page source all the content is there but nothing is showing up on the actual page.
Here is my code rss.php
<?php
ini_set('display_errors', 1);
header("Content-type: text/xml");
include("config.php");
global $NEWS;
$str = '<?xml version="1.0" encoding="utf-8"?>';
$str.= '<rss version="2.0">';
$str.='<channel>';
$sql = "SELECT * FROM $NEWS";
$result = mysql_query($sql) or die ($sql."".mysql_error());
while($row = mysql_fetch_object($result)){
$str.= '<item>';
$str.=' <a href="'.getSEOLink(13).'&article='.$row->id.'">';
$str.= '<title>'.$row->title.'</title></a>';
$str.= '<description><![CDATA['.$row->content. ']]></description>';
$str.= '</item>';
}
$str .='</channel>';
$str .='</rss>';
echo $str;
?>
Why not make use of asXML of SimpleXMLElement ?
<?php
ini_set('display_errors', 1);
include("config.php");
global $NEWS;
$str='<channel>';
$sql = "SELECT * FROM $NEWS";
$result = mysql_query($sql) or die ($sql."".mysql_error());
while($row = mysql_fetch_object($result)){
$str.= '<item>';
$str.=' <a href="'.getSEOLink(13).'&article='.$row->id.'">';
$str.= '<title>'.$row->title.'</title></a>';
$str.= '<description><![CDATA['.$row->content. ']]></description>';
$str.= '</item>';
}
$str .='</channel>';
$xml=new SimpleXMLElement($str);
echo $xml->asXML();
You are apparently generating valid XML (thus your browser is not complaining) but not valid RSS (thus feed readers won't be able to read your stuff). For instance, <a> is not a valid RSS tag and definitively not a child of <item>.
Copy the generated XML (not the PHP source code) and validate it with your favourite RSS validator (e.g. W3C Feed Validation Service).

Take form data and write it to XML file

I am trying to take form data (via _POST) and write it to a document using SimpleXML. This is what I have tried and I can't seem to get it to work.
<?php
$title = $_POST['title'];
$link = $_POST['link'];
$description = $_POST['description'];
$rss = new SimpleXMLElement($xmlstr);
$rss->loadfile("feed.xml");
$item = $rss->channel->addChild('item');
$item->addChild('title', $title);
$item->addChild('link', $link);
$item->addChild('description', $description);
echo $rss->asXML();
header("Location: /success.html");
exit;
?>
Any help or a point in the right direction would be much appreciated.
You use the asXML() function wrong. If you want to write your XML to a file, you must pass a filename parameter to it. Check the SimpleXMLElement::asXML manual
so your code line oututing xml should be changed from
echo $rss->asXML();
to
$rss->asXML('myNewlyCreatedXML.xml');
rather than using SimpleXMLElement you can create XML directly like this
$xml = '<?xml version="1.0" encoding="utf-8"?>';
$xml .= '<item>';
$xml .= '<title>'.$title.'</title>';
$xml .= '<link>'.$title.'</link>';
$xml .= '<description>'.$title.'</description>';
$xml .= '</item>';
$xml_file = "feed.xml";
file_put_contents($xml_file,$xml);
may this will help you
There are a few problems with your code
<?php
$title = $_POST['title'];
$link = $_POST['link'];
$description = $_POST['description'];
//$rss = new SimpleXMLElement($xmlstr); // need to have $xmlstr defined before you construct the simpleXML
//$rss->loadfile("feed.xml");
//easier to just load the file when creating your XML object
$rss = new SimpleXML("feed.xml",null,true) // url/path, options, is_url
$item = $rss->channel->addChild('item');
$item->addChild('title', $title);
$item->addChild('link', $link);
$item->addChild('description', $description);
//header("Location: /success.html");
//if you want to redirect you should put a timer on it and echo afterwards but by
//this time if something went wrong there will be output already sent,
//so you can't send more headers, i.e. the next line will cause an error
header('refresh: 4; URL=/success.html');
echo $rss->asXML(); // you may want to output to a file, rather than the client
// $rss->asXML('outfputfile.xml');
exit;
?>

PHP + XML - how to rename and delete XML elements using SimpleXML or DOMDocument?

I've had some success due to the help of StackOverflow community to modify a complex XML source for use with jsTree. However now that I have data that is usable, it is only so if i manually edit the XML to do the following :
Rename all <user> tags to <item>
Remove some elements before the first <user> tag
insert an 'encoding=UTF-8' into the XML opener
and lastly modify the <response> (opening XML tag) to <root>
XML File Example : SampleXML
I have read and read through so many pages on here and google but cannot find a method to achieve the above items.
Point (2) I have found out that by loading it via SimpleXML and using UNSET i can delete the portions I do not require, however I am still having troubles with the rest.
I thought I could perhaps modify the source with SimpleXML (that I am more familiar with) and then continue to modify the code via the help I had been provided before.
<?php
$s = file_get_contents('http://www.fluffyduck.com.au/sampleXML.xml');
$doc1 = simplexml_load_string($s);
unset($doc1->row);
unset($doc1->display);
#$moo = $doc1->user;
echo '<textarea>';
echo $doc1->asXML();
echo '</textarea>';
$doc = new DOMDocument();
$doc->loadXML($doc1);
$users = $doc->getElementsByTagName("user");
foreach ($users as $user)
{
if ($user->hasAttributes())
{
// create content node
$content = $user->appendChild($doc->createElement("content"));
// transform attributes into content elements
for ($i = 0; $i < $user->attributes->length; $i++)
{
$attr = $user->attributes->item($i);
if (strtolower($attr->name) != "id")
{
if ($user->removeAttribute($attr->name))
{
if($attr->name == "username") {
$content->appendChild($doc->createElement('name', $attr->value));
} else {
$content->appendChild($doc->createElement($attr->name, $attr->value));
}
$i--;
}
}
}
}
}
$doc->saveXML();
header("Content-Type: text/xml");
echo $doc->saveXML();
?>
Using recursion, you can create a brand new document based on the input, solving all your points at once:
Code
<?php
$input = file_get_contents('http://www.fluffyduck.com.au/sampleXML.xml');
$inputDoc = new DOMDocument();
$inputDoc->loadXML($input);
$outputDoc = new DOMDocument("1.0", "utf-8");
$outputDoc->appendChild($outputDoc->createElement("root"));
function ConvertUserToItem($outputDoc, $inputNode, $outputNode)
{
if ($inputNode->hasChildNodes())
{
foreach ($inputNode->childNodes as $inputChild)
{
if (strtolower($inputChild->nodeName) == "user")
{
$outputChild = $outputDoc->createElement("item");
$outputNode->appendChild($outputChild);
// read input attributes and convert them to nodes
if ($inputChild->hasAttributes())
{
$outputContent = $outputDoc->createElement("content");
foreach ($inputChild->attributes as $attribute)
{
if (strtolower($attribute->name) != "id")
{
$outputContent->appendChild($outputDoc->createElement($attribute->name, $attribute->value));
}
else
{
$outputChild->setAttribute($attribute->name, $attribute->value);
}
}
$outputChild->appendChild($outputContent);
}
// recursive call
ConvertUserToItem($outputDoc, $inputChild, $outputChild);
}
}
}
}
ConvertUserToItem($outputDoc, $inputDoc->documentElement, $outputDoc->documentElement);
header("Content-Type: text/xml; charset=" . $outputDoc->encoding);
echo $outputDoc->saveXML();
?>
Output
<?xml version="1.0" encoding="utf-8"?>
<root>
<item id="41">
<content>
<username>bsmain</username>
<firstname>Boss</firstname>
<lastname>MyTest</lastname>
<fullname>Test Name</fullname>
<email>lalal#test.com</email>
<logins>1964</logins>
<lastseen>11/09/2012</lastseen>
</content>
<item id="61">
<content>
<username>underling</username>
<firstname>Under</firstname>
<lastname>MyTest</lastname>
<fullname>Test Name</fullname>
<email>lalal#test.com</email>
<logins>4</logins>
<lastseen>08/09/2009</lastseen>
</content>
</item>
...

extracting multiple tags from xml using PHP

Here is my address.xml
<?xml version="1.0" ?>
<!--Sample XML document -->
<AddressBook>
<Addressentry>
<firstName>jack</firstName>
<lastName>S</lastName>
<Address>2899,Ray Road</Address>
<Email>jkjsvsdka#ghu.edu</Email>
</Addressentry>
<Addressentry>
<firstName>Sid</firstName>
<lastName>K</lastName>
<Address>238,Baseline Road,TX</Address>
<Email>sk#ghu.edu</Email>
<Email>sk#gmail.com</Email>
</Addressentry>
<Addressentry>
<firstName>Satya</firstName>
<lastName>Yar</lastName>
<Address>6,Rural Road,Tempe,AZ</Address>
<Email>syarlag#ghu.edu</Email>
<Email>ssya#gmail.com</Email>
<Email>satag#yahoo.com</Email>
</Addressentry>
</AddressBook>
I am trying to load all the entries using PHP code as below. Each addressentry can have one or more tags. Right now from the code below I am able to extract only one tag. My question is how do I extract all tags associated with particular Addressentry. that is I want to print all emails on the same line.
<?php
$theData = simplexml_load_File("address.xml");
foreach($theData->Addressentry as $theAddress) {
$theFirstName = $theAddress->firstName;
$theLastName = $theAddress->lastName;
$theAdd = $theAddress->Address;
echo "<p>".$theFirstName."
".$theLastName."<br/>
".$theAdd."<br/>
".$theAddress->Email."<br/>
</p>";
unset($theFirstName);
unset($theLastName);
unset($theAdd);
unset($theEmail);
}
?>
Any help would be appreciated
$emails = array();
foreach ($theAddress->Email as $email) {
$emails[] = $email;
}
echo "<p>".$theFirstName."
".$theLastName."<br/>
".$theAdd."<br/>
".implode(', ', $emails)."<br/>
</p>";

Categories