I would like my CDATA section display the result of a function that generates a text from an sql query.
Create sql query and call function createXMLfile:
$statement = $connection->query("SELECT * FROM events ORDER BY ID DESC LIMIT 1");
$statement->execute();
$eventArray = array();
while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
array_push($eventArray, $row);
}
createXMLfile($eventArray);
Function that generate text from my sql query:
<?php
function write_records($eventArray) {
for($i=0; $i<count($eventArray); $i++){
$name = $eventArray[$i]['event_name'];
$city = $eventArray[$i]['event_city'];
?>A new event <?php echo $eventArray[$i]['event_name'];?> is coming in <?php $eventArray[$i]['event_city'];?>.<?php
}
return $eventArray;
}
?>
Function that create XML file (i use implode for convert array to a string):
function createXMLfile($eventArray){
$filePath = 'event.xml';
$content = implode(' ', write_records($eventArray));
$dom = new DOMDocument('1.0', 'utf-8');
$root = $dom->createElement('INCIDENTS');
for($i=0; $i<count($eventArray); $i++){
$eventName = $eventArray[$i]['event_name'];
$eventCity = $eventArray[$i]['event_city'];
$eventXml = $dom->createElement('INCIDENT');
$name = $dom->createElement('EVENT', $eventName);
$eventXml->appendChild($name);
$city = $dom->createElement('CITY', $eventCity);
$eventXml->appendChild($city);
$eventXml->appendChild(new DOMElement('COMMENTAIRE'))->appendChild(new DOMCdataSection($content));
$root->appendChild($eventXml);
}
$dom->appendChild($root);
$dom->save($filePath);
}
XML file is generated but CDATA section display only this :
<![CDATA[Array]]>
Please can you tell me what's wrong ? Thanks for your help.
EDIT:
function createXMLfile($eventArray){
$filePath = 'event.xml';
$content = implode(' ', write_records($eventArray[0]));
$dom = new DOMDocument('1.0', 'utf-8');
$root = $dom->createElement('INCIDENTS');
for($i=0; $i<count($eventArray); $i++){
$eventName = $eventArray[$i]['event_name'];
$eventCity = $eventArray[$i]['event_city'];
$eventXml = $dom->createElement('INCIDENT');
$name = $dom->createElement('EVENT', $eventName);
$eventXml->appendChild($name);
$city = $dom->createElement('CITY', $eventCity);
$eventXml->appendChild($city);
$eventXml->appendChild(new DOMElement('COMMENTAIRE'))->appendChild(new DOMCdataSection($content));
$root->appendChild($eventXml);
}
$dom->appendChild($root);
$dom->save($filePath);
}
Now sql values are displayed in CDATA section but not the generated text from function write_records($eventArray).
<![CDATA[concert Miami]]>
And i would like :
<![CDATA[A new concert is coming in Miami]]>
print_r($eventArray); give me same result :
$statement = $connection->query("SELECT * FROM events ORDER BY ID DESC LIMIT 1");
$statement->execute();
$eventArray = array();
while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
array_push($eventArray, $row);
}
print_r($eventArray);
createXMLfile($eventArray);
Apache Log say PHP Notice: Undefined offset :0 from variables values in function write_records($eventArray)
Related
I am trying to create XML using DOMDocument from database table. All field types are showing in XML node except BLOB Type.
Below what I did:
$rs = ibase_query("SELECT * FROM mytable");
$coln = ibase_num_fields($rs);
$fieldnames = array();
for ($i = 0; $i < $coln; $i++) {
$col_info = ibase_field_info($rs, $i);
$fieldnames[] = array('name' => $col_info['name'], 'type' => $col_info['type']);
}
$doc = new DOMDocument('1.0');
$sth = ibase_query($dbh, $stmt);
$doc->formatOutput = true;
$root = $doc->createElement('FA_ARTIKEL');
$root = $doc->appendChild($root);
while ($row = ibase_fetch_object($sth, IBASE_TEXT)) {
$title = $doc->createElement('RECORD');
$title = $root->appendChild($title);
$text = $doc->createTextNode('');
$text = $title->appendChild($text);
foreach ($fieldnames as $value) {
switch ($value['type']) {
case 'VARCHAR':
$rtitle = $doc->createElement($value['name']);
$rtitle = $title->appendChild($rtitle);
$rtext = $doc->createTextNode($row->$value['name']);
$rtext = $rtitle->appendChild($rtext);
break;
case 'BLOB':
$rbtitle = $doc->createElement($value['name']);
$rbtitle = $title->appendChild($rbtitle);
$rbtext = $doc->createTextNode($row->$value['name']);
$rbtext = $rbtitle->appendChild($rbtext);
break;
default:
if ($row->$value['name']) {
$rtitle = $doc->createElement($value['name']);
$rtitle = $title->appendChild($rtitle);
$rtext = $doc->createTextNode($row->$value['name']);
$rtext = $rtitle->appendChild($rtext);
} else {
$rtitle = $doc->createElement($value['name']);
$rtitle = $title->appendChild($rtitle);
$rtext = $doc->createTextNode('0');
$rtext = $rtitle->appendChild($rtext);
}
break;
}
}
}
Header('Content-type: text/xml');
echo $doc->saveXML() . "\n";
ibase_free_result($sth);
ibase_close($dbh);
I tried with SimpleXMLElement also but it also failed. What I am missing?
My Database is Firebird and I set BLOB fields as
BLOB SUB_TYPE 1 SEGMENT SIZE 16384
PHPs DOMDocument expects UTF-8 strings. It is possible that the blob contains control characters/invalid unicode sequences. Try to put the data that breaks the XML into a variable and reduce your problem to the absolute minimum.
$blobData = $record['blobField'];
$document = new DOMDocument();
$document
->appendChild($document->createElement('foo'))
->appendChild($document->createTextNode($blobData));
echo $document->saveXml();
This way you can see if the blob data is really the problem or merely a symptom.
If the BLOB contains binary data you will need to convert it into a TEXT format. Atom feeds for example urlencode binary data that they want to embed. In this you will need to decode the value in the reading program.
I've made this program that updates an xml file based on entries in an array.
I've used FILE_APPEND because the entries are more than one and otherwise file gets overwritten. But the problem is the xml version tag prints out as many times as many entries are there.
So i want to remove this tag.
Here's my program:-
<?php
include 'array.php';
$xmlW = new XMLWriter();
$file = 'entry-'. date('M-D-Y') .'.xml';
/*$setting = new XMLWriterSettings();
$setting->OmitXmlDeclaration = true;*/
foreach($data as $d) {
if(in_array ($d['Mode'], array('ccAV','MB','Paypal','E2P'))) {
$recordType = 'receipt';
$xml_object = simplexml_load_file ('receipt.xml');
} else {
$xml_object = simplexml_load_file ('journal.xml');
$recordType = 'journal';
}
$xml_object->xpath("/ENVELOPE/BODY/IMPORTDATA/REQUESTDATA/TALLYMESSAGE/VOUCHER")[0]->DATE = $d['InvoiceDate'];
$xml_object->xpath("/ENVELOPE/BODY/IMPORTDATA/REQUESTDATA/TALLYMESSAGE/VOUCHER")[0]->NARRATION = 'Rahul';
$xml_object->xpath("/ENVELOPE/BODY/IMPORTDATA/REQUESTDATA/TALLYMESSAGE/VOUCHER")[0]->EFFECTIVEDATE = $d['InvoiceDate'];
$xml_object->xpath("/ENVELOPE/BODY/IMPORTDATA/REQUESTDATA/TALLYMESSAGE/VOUCHER/ALLLEDGERENTRIES.LIST")[0]->LEDGERNAME = $d['Mode'];
$xml_object->xpath("/ENVELOPE/BODY/IMPORTDATA/REQUESTDATA/TALLYMESSAGE/VOUCHER/ALLLEDGERENTRIES.LIST")[0]->AMOUNT = 'Rahul';
$xml_object->xpath("/ENVELOPE/BODY/IMPORTDATA/REQUESTDATA/TALLYMESSAGE/VOUCHER/ALLLEDGERENTRIES.LIST")[1]->AMOUNT = 'Rahul';
$xml_object->xpath("/ENVELOPE/BODY/IMPORTDATA/REQUESTDATA/TALLYMESSAGE/VOUCHER/ALLLEDGERENTRIES.LIST")[2]->AMOUNT = 'Rahul';
$xml_object->xpath("/ENVELOPE/BODY/IMPORTDATA/REQUESTDATA/TALLYMESSAGE/VOUCHER/ALLLEDGERENTRIES.LIST/BANKALLOCATIONS.LIST")[0]->DATE = 'Rahul';
$xml_object->xpath("/ENVELOPE/BODY/IMPORTDATA/REQUESTDATA/TALLYMESSAGE/VOUCHER/ALLLEDGERENTRIES.LIST/BANKALLOCATIONS.LIST")[0]->INSTRUMENTDATE = 'Rahul';
$xml_object->xpath("/ENVELOPE/BODY/IMPORTDATA/REQUESTDATA/TALLYMESSAGE/VOUCHER/ALLLEDGERENTRIES.LIST/BANKALLOCATIONS.LIST")[0]->AMOUNT = 'Rahul';
$xml = $xml_object->asXML();
file_put_contents($file, $xml, FILE_APPEND);
}
?>
Thanks for the help.
Hello I want to parse a HTML table and assign those values to php variables so that i can insert them in to mysql database
I have tried some html parsing methods like dom_html_parsing but as a beginer i am getting much confused, i would be gald if some provides me some hint on this so that i can code
Parsing code i used is
include('simple_html_dom.php');
$dom = str_get_html($result);
$table = array();
$html = str_get_html($result);
foreach($html->find('tr') as $row) {
$time = $row->find('td',-1)->plaintext;
$title = $row->find('td',0)->plaintext;
$title0 = $row->find('td',1)->plaintext;
$title1 = $row->find('td',2)->plaintext;
$title2 = $row->find('td',3)->plaintext;
$title3 = $row->find('td',4)->plaintext;
$title4 = $row->find('td',5)->plaintext;
$title5 = $row->find('td',6)->plaintext;
$table[$title][$title0][$title1][$title2][$title3][$title4][$title3] = true;
}
echo '<pre>';
print_r($table);
echo '</pre>';
the arrays are printing but i do not know how to insert those particular values in to mysql database, i want to assign those values to variables first so that i can insert in to the database and the format i need is shown above, name and fathername & htno are printed only once in html table but i need it to be repeated with each row of table
Please help me
$table_data = array();
$dom = new DOMDocument();
$dom->loadHTML($html_string);
$rows = $dom->getElementsByTagName('tr');
for ($i = 0; $i < $rows->length; $i++) {
$cells = $rows->item($i)->getElementsByTagName('td');
for ($j = 0; $j < $cells->length; $j++) {
$table_data[$i][$j] = $cells->item($j)->textContent;
}
}
//print_r($table_data);
You can use phpquery. It's similar to jQuery, but for PHP.
I'm trying to use xpath in conjunction with DOMDocument to try and parse my xml and insert into a table.
All my variables are inserting correctly other than $halftimescore - why is this?
Here is my code:
<?php
define('INCLUDE_CHECK',true);
require 'db.class.php';
$dom = new DOMDocument();
$dom ->load('main.xml');
$xpath = new DOMXPath($dom);
$queryResult = $xpath->query('//live/Match/Results/Result[#name="HT"]');
foreach($queryResult as $resulty) {
$halftimescore=$resulty->getAttribute("value");
}
$Match = $dom->getElementsByTagName("Match");
foreach ($Match as $match) {
$matchid = $match->getAttribute("id");
$home = $match->getElementsByTagName("Home");
$hometeam = $home->item(0)->getAttribute("name");
$homeid = $home->item(0)->getAttribute("id");
$away = $match->getElementsByTagName("Away");
$awayid = $away->item(0)->getAttribute("id");
$awayteam = $away->item(0)->getAttribute("name");
$leaguename = $match->getElementsByTagName("league");
$league = $leaguename->item(0)->nodeValue;
$leagueid = $leaguename->item(0)->getAttribute("id");
foreach ($match->getElementsByTagName('Result') as $result) {
$resulttype = $result->getAttribute("name");
$score = $result->getAttribute("value");
$scoreid = $result->getAttribute("value");
}
mysql_query("
INSERT INTO blabla
(home_team, match_id, ht_score, away_team)
VALUES
('".$hometeam."', '".$matchid."', '".$halftimescore."', '".$awayteam."')
");
}
Because you populated $halftimescore outside the main loop, in a loop of its own, it will only have one value (the last value) because each iteration overwrites the previous.
What you need to do instead is run the XPath query within the main loop, with a base node of the current node, like this:
// ...
$xpath = new DOMXPath($dom);
/*
Remove these lines from here...
$queryResult = $xpath->query('//live/Match/Results/Result[#name="HT"]');
foreach($queryResult as $resulty) {
$halftimescore=$resulty->getAttribute("value");
}
*/
$Match = $dom->getElementsByTagName("Match");
foreach ($Match as $match) {
// and do the query here instead:
$result = $xpath->query('./Results/Result[#name="HT"]', $match);
if ($result->length < 1) {
// handle this error - the node was not found
}
$halftimescore = $result->item(0)->getAttribute("value");
// ...
i want to create dynamic banner rotater wih php ajax i want to pass the mysql_fetch_array() to an array to create a new array() to create xml response..........
here is my code
$sql = mysql_query("SELECT * FROM ads");
header('Content-type: text/xml');
echo '<?xml version="1.0" ?>';
while($row = mysql_fetch_array($sql)){
$title = $row['title'];
$img = $row['file'];
$body = $row['body'];
$ban = '<b>'.$title.'</b><br><br><img src="ads/'.$img.'"><br><br>'.$body;
$banners = array(
$ban,
);
$html = $banners[array_rand($banners)];
}
<banner>
<content><?php echo htmlentities($html); ?></content>
<reload>3000</reload>
</banner>
but it is return only one ad not return multiple ads how can i fix that
The proble is here: $banners = array($ban);. What you're trying to do is include all the ads in the $banners array as an entry but you are failing to achieve that.
The correct code for including an entry in an array would be $banner[] = $ban. That way each ad that comes as a result from your query will be stored as an individual entry.
So the correct code would be:
$sql = mysql_query("SELECT * FROM ads");
$banner = array(); //Define the array before trying to add elements.
header('Content-type: text/xml');
while($row = mysql_fetch_array($sql))
{
$title = $row['title'];
$img = $row['file'];
$body = $row['body'];
$ban = '<b>'.$title.'</b><br><br><img src="ads/'.$img.'"><br><br>'.$body;
$banner[] = $ban; //Adding a new entry at the end.
$html = array_rand($banner); //Getting a random entry.
}
Use this in the while loop:
$banners[] = $ban
Instead of
$banners = array(
$ban,
);
and
$html = array_rand($banners);
instead of
$html = $banners[array_rand($banners)];
And to what bzabhi said, define your
$banners = array();
before the while loop, and the randomization part has to go after the loop.