hey there i have an xml file that has what i need to do is to add an event with same location name A
<timetable>
<location name="A" >
<event >
<title>EVENT TITLE </title>
<subtitle>Amman -text </subtitle>
<description>Amman -text </description>
</event>
</location>
</timetable>
so it can be like this
<timetable>
<location name="A" >
<event >
<title>EVENT TITLE </title>
<subtitle>Amman -text </subtitle>
<description>Amman -text </description>
</event>
<event >
<title>EVENT TITLE </title>
<subtitle>Amman -text </subtitle>
<description>Amman -text </description>
</event>
</location>
</timetable>
i got stuck in my php code where i want to cheack if the event is created or not if its created modify my xml with name of the event and add the new one
this is my full php inserting code `
if(isset($_GET['coname'])){
$coid = $_GET['id'];
$cname=$_GET['coname'];
$title = $_POST ['title'];
$sub = $_POST ['sub'];
$description = $_POST ['description'];
$location = $_POST ['location'];
$event = $_POST ['event'] ;
$str =$_POST ['str'] ;
$end =$_POST ['end'] ;
$topic = $_POST ['topic'] ;
$sql="INSERT INTO timeline (title,sub,description,location,event,str,end,topic,coid)
VALUES
('$title','$sub','$location','$location','$event','$str','$end','$topic','$coid')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
$q = mysqli_query($con,"SELECT * FROM timeline where coid = $coid") or die(mysqli_error());
$xml = '<timetable start="'.$st.'" end="'.$en.'" interval="'.$in.'" title="'.$da.'">';
while($r = mysqli_fetch_array($q)){
$loc=$r['topic'];
$evns=$r['str'];
$evne= $r['end'];
$xml .= '<location name="'.$loc.'" subtext=" ">';
$xml .= '<event start="'.$evns.'" end="'.$evne.'">';
$xml .= "<title>".$r['title']."</title>";
$xml .= "<subtitle>".$r['location']."</subtitle>";
$xml .= "<description>".$r['description']."</description>";
$xml .= "</event>";
$xml .= "</location>";
}
$xml .= "</timetable>";
$sxe = new SimpleXMLElement($xml);
$sxe->asXML('xml/'.$cname.'.xml'); `
Amer, rather than creating the XML from strings, I'd use the simplexml methods:
Inserting a new <event> in existing XML:
$xml = simplexml_load_string($x); // assume XML in $x
$loc = $xml->xpath("location[#name = 'A']")[0]; // select <location> with name = A
$event = $loc->addChild("event");
$event->addAttribute("start", "2013-05-20 10:00:00");
$event->addAttribute("end", "2013-05-20 14:30:00");
$event->addChild("title", "some title");
$event->addChild("subtitle", "some subtitle");
$event->addChild("description", "some description");
see it working: http://codepad.viper-7.com/12xtVD
From what I understand, you want to create a child element. This is how I would go about doing this:
PHP:
$eleone=$_POST['elementone'];
$eletwo=$_POST['elementtwo'];
$file = "verbs.xml";
$openf = fopen($file, "c+") or die ("Cannot open file");
$str = fread ($openf, filesize($file));
$xml = new DOMDocument('1.0', 'iso-8859-1');
$xml->formatOutput=TRUE;
$xml->preserveWhiteSpace = FALSE;
$xml ->loadXML($openf) or die ("There has been an error with opening the XML file. Our team has been notified and will start working to fix this problem.");
//this is the original document
echo "<xmp>OLD:\n". $xml->saveXML(). "<xmp>";
//this is how you get the document element
$root= $xml ->documentElement;
$firstnode= $root->firstChild;
//good stuff right here; how to make a node
$ori= $firstnode->childNodes->item(2);
$eleadd= $xml->createElement($elementone);
$eleaddt= $xml->createTextNode($//what gets shown in $eleadd );
$eleadd->appendChild("$idt");
If you don't want all of this, you may be able to delete some non-crucial things like the parent elements. If you need more information, http://www.phpeveryday.com/articles/PHP-XML-Adding-XML-Nodes-P414.html is the place to go, or where I found my information.
Related
I'm trying to get an RSS feed, change some text, and then serve it again as an RSS feed. However, the code I've written doesn't validate properly. I get these errors:
line 3, column 0: Missing rss attribute: version
line 14, column 6: Undefined item element: content (10 occurrences)
Here is my code:
<?php
header("Content-type: text/xml");
echo "<?xml version='1.0' encoding='UTF-8'?>
<?xml-stylesheet type='text/xsl'?>
<?xml-stylesheet type='text/xsl' media='screen'
href='/~d/styles/rss2full.xsl'?>
<rss xmlns:content='http://purl.org/rss/1.0/modules/content/'>
<channel>
<title>Blaakdeer</title>
<description>Blog RSS</description>
<language>en-us</language>
";
$html = "";
$url = "http://feeds.feedburner.com/vga4a/mPSm";
$xml = simplexml_load_file($url);
for ($i = 0; $i < 10; $i++){
$title = $xml->channel->item[$i]->title;
$description = $xml->channel->item[$i]->description;
$content = $xml->channel->item[$i]->children("content", true);
$content = preg_replace("/The post.*/","", $content);
echo "<item>
<title>$title</title>
<description>$description</description>
<content>$content</content>
</item>";
}
echo "</channel></rss>";
Just as you don't treat XML as a string when parsing it, you don't treat it as as string when you create it. Use the proper tools to create your XML; in this case, the DomDocument class.
You had a number of problems with your XML; biggest is that you were creating a <content> element, but the original RSS had a <content:encoded> element. That means the element name is encoded but it's in the content namespace. Big difference between that and an element named content. I've added comments to explain the other steps.
<?php
// create the XML document with version and encoding
$xml = new DomDocument("1.0", "UTF-8");
$xml->formatOutput = true;
// add the stylesheet PI
$xml->appendChild(
$xml->createProcessingInstruction(
'xml-stylesheet',
'type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"'
)
);
// create the root element
$root = $xml->appendChild($xml->createElement('rss'));
// add the version attribute
$v = $root->appendChild($xml->createAttribute('version'));
$v->appendChild($xml->createTextNode('2.0'));
// add the namespace
$root->setAttributeNS(
'http://www.w3.org/2000/xmlns/',
'xmlns:content',
'http://purl.org/rss/1.0/modules/content/'
);
// create some child elements
$ch = $root->appendChild($xml->createElement('channel'));
// specify the text directly as second argument to
// createElement because it doesn't need escaping
$ch->appendChild($xml->createElement('title', 'Blaakdeer'));
$ch->appendChild($xml->createElement('description', 'Blog RSS'));
$ch->appendChild($xml->createElement('language', 'en-us'));
$url = "http://feeds.feedburner.com/vga4a/mPSm";
$rss = simplexml_load_file($url);
for ($i = 0; $i < 10; $i++) {
if (empty($rss->channel->item[$i])) {
continue;
}
$title = $rss->channel->item[$i]->title;
$description = $rss->channel->item[$i]->description;
$content = $rss->channel->item[$i]->children("content", true);
$content = preg_replace("/The post.*/","", $content);
$item_el = $ch->appendChild($xml->createElement('item'));
$title_el = $item_el->appendChild($xml->createElement('title'));
// this stuff is unknown so it has to be escaped
// so have to create a separate text node
$title_el->appendChild($xml->createTextNode($title));
$desc_el = $item_el->appendChild($xml->createElement('description'));
// the other alternative is to create a cdata section
$desc_el->appendChild($xml->createCDataSection($description));
// the content:encoded element is not the same as a content element
// the element must be created with the proper namespace prefix
$cont_el = $item_el->appendChild(
$xml->createElementNS(
'http://purl.org/rss/1.0/modules/content/',
'content:encoded'
)
);
$cont_el->appendChild($xml->createCDataSection($content));
}
header("Content-type: text/xml");
echo $xml->saveXML();
The first error is just a missing attribute, easy enough:
<rss version="2.0" ...>
For the <p> and other HTML elements, you need to escape them. The file should look like this:
<p>...
There are other ways, but this is the easiest way. In PHP you can just call a function to encode entities.
$output .= htmlspecialchars(" <p>Paragraph</p> ");
As for the <content> tag problem, it should be <description> instead. The <content> tag currently generates two errors. Changing it to <description> in both places should fix both errors.
Otherwise it looks like you understand the basics. You <open> and </close> tags and those have to match. You can also use what is called empty tags: <empty/> which exist on their own but to not include content and no closing tag.
I have two XML files: one from a client and one created from a db query. The db XML file has this structure:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<metadata xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<tags>
<title>Wordsleuth (2006, volume 3, 4): The Dictionary: Disapproving Schoolmarm or Accurate Record?</title>
<alias>favart/wordsleuth-2006-volume-3-4-the-dictionary-disapproving-schoolmarm-or-accurate-record</alias>
<id>4361</id>
</tags>
</metadata>
The client XML has this structure:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<metadata xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<tags>
<title>Wordsleuth (2006, vol. 3, 4): The Dictionary: Disapproving Schoolmarm or Accurate Record? – Search by Title – Favourite Articles – TERMIUM Plus® – Translation Bureau</title>
<description>A Language Update article on the role that the dictionary plays in language usage.</description>
<keywords>language usage; dictionaries</keywords>
<subject>English language; Terminology</subject>
</tags>
</metadata>
Each with approx 200 'tags' elements. After getting some hints from here and here and referencing the PHP manual my first crack at it produced this:
$client = 'C:\xampp\htdocs\wetkit\sites\all\modules\my_metatags\favart.xml';
$db = 'C:\xampp\htdocs\wetkit\sites\all\modules\my_metatags\tmp\from db\favart_db.xml';
$c_xmlstr = file_get_contents($client);
$d_xmlstr = file_get_contents($db);
$favartdoc_db = new DomDocument('1.0','UTF-8');
$favartdoc_cl = new DomDocument('1.0','UTF-8');
$favartdoc_db->loadXML($d_xmlstr);
$favartdoc_cl->loadXML($c_xmlstr);
for ($i=0;$i==$favartdoc_cl->getElementsByTagName('title')->count; $i++){
$c_nodes = $x_favartdoc_cl->query('/metadata/tags/title');
$c_node = $c_nodes->item($i);
for ($j=0; $j==$favartdoc_db->getElementsByTagName('title')->count; $j++){
$d_nodes = $x_favartdoc_db->query('/metadata/tags/title');
$d_node = $d_nodes->item($j);
if(stripos(trim($c_node->nodeValue), trim($d_node->nodeValue))===0){
$favartdoc_cl->replaceChild($d_node,$c_node);
if($i==($c_nodes->count)){break;};
}
}
$favartdoc_cl->saveXML();
}
This code runs, generates no errors, and does nothing. An echo statement at the end
echo "\n\n" . "THE TOTAL NUMBER OF MATCHES EQUALS " . $i . " IN " . $j . " NODES." . "\n";
generates this message:
THE TOTAL NUMBER OF MATCHES EQUALS 1 IN 1 NODES.
A second simpler approach produced this:
$favartdoc_db = new DomDocument('1.0','UTF-8');
$favartdoc_cl = new DomDocument('1.0','UTF-8');
$favartdoc_db->load($db);
$favartdoc_cl->load($client);
$favartdoc_cl->formatOutput = true;
$c_meta_x = new DOMXpath($favartdoc_cl);
$d_meta_x = new DOMXpath($favartdoc_db);
foreach ($c_meta_x->query('//tags') as $c_tag){
foreach ($d_meta_x->query('//tags') as $d_tag){
if(strncasecmp(trim($c_tag->title), trim($d_tag->title) , strlen(trim($d_tag->title)))===0){
$c_tag->appendChild($d_tag);
}
}
}
$favartdoc_cl->saveXML();
But this generates an error:
exception 'DOMException' with message 'Wrong Document Error'
Suggestions to correct that error, by calling importNode before attaching it to the DOM, still generate the same error.
As you can see I'm trying a different string matching function in each. Ultimately I want to replace the titles in the client XML with those from the db or append the whole tag set from the db XML to the client XML then delete the client title element afterwards.
Any help would be appreciated.
This is what worked for me.
$client = 'some\where\somefile.xml';
$db = 'some\where\someOtherfile.xml';
$c_xmlstr = file_get_contents($client);
$d_xmlstr = file_get_contents($db);
$doc_db = new DomDocument('1.0','UTF-8');
$doc_cl = new DomDocument('1.0','UTF-8');
$doc_db->loadXML($d_xmlstr);
$fdoc_cl->loadXML($c_xmlstr);
$x_doc_db = new DOMXpath($doc_db);
$x_doc_cl = new DOMXpath($doc_cl);
$c_nodes = $x_doc_cl->query('/metadata/tags');
$c_nodes_titles = $x_doc_cl->query('/metadata/tags/title');
for($i=0;$i<=$c_nodes->length;++$i){
$c_node = $c_nodes->item($i);
$c_node_title = $c_nodes_titles->item($i);
$d_nodes = $x_doc_db->query('/metadata/tags');
$d_nodes_titles = $x_doc_db->query('/metadata/tags/title');
$d_nodes_ids = $x_doc_db->query('/metadata/tags/id');
for($j=0;$j<=$d_nodes->length;++$j){
$d_node_title = $d_nodes_titles->item($j);
$d_node_id = $d_nodes_ids->item($j);
if(strncasecmp(trim($c_node_title->textContent),trim($d_node_title->textContent) , strlen(trim($d_node_title->textContent)))===0 && trim($c_node_title->textContent)===trim($d_node_title->textContent)){
$db_id = $doc_cl->createElement("db_id");
$db_id_val = $doc_cl->createTextNode($d_node_id->nodeValue);
if(!is_null($c_node)){$c_node->appendChild($db_id);}
if(!is_null($c_node)){$c_node->appendChild($db_id_val);}
}
}
if($i===($c_nodes->count) && $j===($d_nodes->count)){break;};
}
$doc_cl->saveXML();
I've got the following problem:
I have a csv file, that I can convert to XML via a php script.
This way, every field goes under the same row in the xml, and I want the product_sku field go under a different row, for example call it SKU_row.
The CSV looks like this:
my CSV file
The XML looks like this:
my XML file
PHP file code that I run to convert the CSV to XML:
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', true);
ini_set('auto_detect_line_endings', true);
function PrepareXMLName($PrepareString)
{
$PrepareString = str_replace(" ","",$PrepareString);
$PrepareString = preg_replace('#\W#', '', $PrepareString);
$PrepareString = str_replace("ZSPAZESZ","",$PrepareString);
$PrepareString = strtolower($PrepareString);
return $PrepareString;
}
$inputFilename = 'faszom.csv';
$outputFilename = 'faszom.xml';
// Open csv to read
$inputFile = fopen($inputFilename, 'rt');
// Get the headers of the file
$headers = fgetcsv($inputFile);
// Create a new dom document with pretty formatting
$doc = new DomDocument();
$doc->formatOutput = true;
// Add a root node to the document
$root = $doc->createElement('rows');
$root = $doc->appendChild($root);
// Loop through each row creating a <row> node with the correct data
while (($row = fgetcsv($inputFile)) !== FALSE)
{
$container = $doc->createElement('row');
foreach ($headers as $i => $header)
{
$header = str_replace(chr(32),"_",trim($header));
$header = strtolower($header);
if($header==''){ $header = 'empty';}
$header = PrepareXMLName($header);
if(is_numeric($header)) { $header = "number-". $header; }
//echo "HERE: " . $header . "<br />";
$child = $doc->createElement($header);
$child = $container->appendChild($child);
$value = $doc->createTextNode($row[$i]);
$value = $child->appendChild($value);
}
$root->appendChild($container);
}
header("Content-type: text/xml");
$strxml = $doc->saveXML();
$handle = fopen($outputFilename, "w");
fwrite($handle, $strxml);
fclose($handle);
echo $doc->saveXML();
How can I do in this PHP file, to let it put the product_sku fields under a different row, to be it separated from the row in which customer data's are?
XML allows you to group on a further level. So instead of your flat row model:
<rows>
<row>
<product_sku>L162L</product_sku>
<order_entity_id>31</order_entity_id>
<order_customer_firstname>Teszt</order_customer_firstname>
<product_qty_ordered>1.0000</product_qty_ordered>
</row>
You can group further on depending on the context of the data, for example by order, product and customer:
<rows>
<row>
<product>
<sku>L162L</sku>
<qty_ordered>1.0000</qty_ordered>
<product>
<order>
<entity_id>31</entity_id>
<customer>
<firstname>Teszt</firstname>
</customer>
</order>
</row>
But this depends entirely of what you want and from your question I don't see any reason on why to do it this, that or any other way nor what stands in your way to do whatever you want.
http://seosailor.com/beta2/articles/showrss this url give error Extra content at the end of the document on chrome
my code is this
function showrss() {
header("Content-Type: application/xml; charset=ISO-8859-1");
$query_items = "select * from articles";
$result_items = mysql_query ($query_items) or die("Some error: ".mysql_error());
$xml = '<?xml version="1.0" encoding="ISO-8859-1" ?><rss version="2.0"><channel>';
while($row = mysql_fetch_array($result_items))
{
//$des = mysql_real_escape_string($row['a_description']);
// $a_des = str_replace(']]>', ']]>',$row['a_description']);
//$a_des = strip_tags($row['a_description']);
// $a_des = preg_replace('/[^a-zA-Z0-9\s]/', '', strip_tags($row['a_description']));
$a_des = htmlspecialchars($row['a_description']);
$xml .= '<item>
<title>'.$row["a_title"].'</title>
<link>'.$row["a_url"].'</link>
<description>'.$a_des.'</description></item>';
} $xml .= '</channel>';
$xml .= '</rss></xml>';
echo $xml;}
That's because of the extra </xml> closing tag at the end (there is no opening <xml> tag).
This question already has answers here:
How to generate XML file dynamically using PHP?
(8 answers)
Closed 8 years ago.
I have a problem in XML files.
I searched through the internet and found lots of examples for my problem but I am not an expert on XML files and couldn't solve my problem. I want to do and XML file and work like RSS FEED. So, I am taking my data from my database and try to create the xml-code. Here what I have in my php file
(and it is not validated because of this problem: Undefined root element: channel)
<?php
include "connection.php";
//create the table with the fields
$rss_table = array();
$query = mysql_query("SELECT * FROM rssfeeds");
while($values_query = mysql_fetch_assoc($query))
{
$rss_table [] = array(
'title' => $values_query['title'],
'description' => $values_query['summary'],
'link' => $values_query['link']
);
}
$doc = new DOMDocument();
$doc->formatOutput = true;
$doc->encoding = "utf-8";
$r = $doc->createElement( "channel" );
$doc->appendChild( $r );
//$i=0;
foreach( $rss_table as $rss )
{
$b = $doc->createElement( "item" );
$title = $doc->createElement( "title" );
$title->appendChild(
$doc->createTextNode( $rss['title'] )
);
$b->appendChild( $title );
$description = $doc->createElement( "description" );
$description->appendChild(
$doc->createTextNode( $rss['description'] )
);
$b->appendChild( $description );
$link = $doc->createElement( "link" );
$link->appendChild(
$doc->createTextNode( $rss['link'] )
);
$b->appendChild( $link );
$r->appendChild( $b );
}
echo $doc->saveXML();
$doc->save("rssfeeds.xml")
?>
I want to have title - link - description
Simple one... nothing more
And here is what I get in rssfeeds.xml file:
<?xml version="1.0" encoding="utf-8"?>
<channel>
<item>
<title>winter week</title>
<description>You can come as you are! </description>
<link>http://tdm2000international.org/tdm2000international/news.php</link>
</item>
<item>
<title>Greek night</title>
<description>elliniki bradua sto magazi</description>
<link>http://tdm2000international.org/tdm2000international/news.php</link>
</item>
<item>
<title>event website</title>
<description>first of december, how is it going?</description>
<link>http://tdm2000international.org/tdm2000international/news.php</link>
</item>
</channel>
Nice format, but it has problem. I do not understand where the problem is.
Any help would be appreciated
(I also check this website for any solution, but I could not found my solution..So, sorry about this post, if it is already exist)
ok I found my one way .. I did it with FILES via php: this is the code if anyone needs help to that:
<?php
include "connection.php";
$myFile = "rss.xml";
$fh = fopen($myFile, 'w') or die("can't open file");
$rss_txt .= '<?xml version="1.0" encoding="utf-8"?>';
$rss_txt .= "<rss version='2.0'>";
$rss_txt .= '<channel>';
$query = mysql_query("SELECT * FROM rssfeeds");
while($values_query = mysql_fetch_assoc($query))
{
$rss_txt .= '<item>';
$rss_txt .= '<title>' .$values_query['title']. '</title>';
$rss_txt .= '<link>' .$values_query['link']. '</link>';
$rss_txt .= '<description>' .$values_query['summary']. '</description>';
$rss_txt .= '</item>';
}
$rss_txt .= '</channel>';
$rss_txt .= '</rss>';
fwrite($fh, $rss_txt);
fclose($fh);
?>