I recently asked this question,
XML structure while creating from MySQL query in PHP. I got the answer I needed but now I have a similar case that is missing just one thing.
I duplicated the code and changed as needed but the category rows are not working.
Here is my code
$xml2 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
$xml2 .= "\r\n";
$xml2 .= "<resources>";
$xml2 .= "<version>1</version>";
$xml2 .= "\r\n";
//select all items in table
$sql2 = "SELECT distinct category, name FROM user where user = '$user' and category is not null order by category";
$result2 = mysql_query($sql2);
if (!$result2) {
die('Invalid query: ' . mysql_error());
}
if(mysql_num_rows($result2)>0){
while($row2 = mysql_fetch_assoc($result2)){
if(!isset($previousRow2) || !isset($previousRow2["category"]) || $previousRow2["category"] != $row2["category"])
{
$xml2 .= "\r\n";
$xml2 .= "<category title=\"" . $row["category"] . "\" />\r\n";
}
$xml2 .= "<item drawable=\"";
$xml2 .= $row2["name"];
$xml2 .= "\" />";
$xml2 .= "\r\n";
$previousRow2 = $row2;
}
}
$xml2 .= "</resources>";
This is outputting this
<category title="" />
<item drawable="bigdx_clean" />
<category title="" />
<item drawable="bluetooth" />
<item drawable="bluetooth_audio" />
<item drawable="browser" />
<item drawable="calculator" />
<item drawable="calendar" />
<item drawable="call_history" />
<item drawable="camera" />
The titles are blank though.
I'm using the same concept of the working code from other question. It's a different query so I must have something wrong with it?
$xml2 .= "<category title=\"" . $row["category"] . "\" />\r\n";
You are accessing $row["category"], but this variable is not defined anywhere. Did you mean $row2?
For what it's worth, $row2 isn't a very descriptive name for a variable. If you are looking for another variable name because $row is taken, perhaps you need to move this into another function, where $row will just be local?
If you are (inadvertently) accessing variables that do not exist, it is likely that your on-screen errors are disabled in your local PHP configuration. It is a good idea to turn these on to aid your development process - you'll find that setting in your php.ini configuration.
Related
I have some problem with converting mysql to xml using php due to my lack knowledge in PHP.
I got this code from a website located here http://www.mightywebdeveloper.com/coding/mysql-to-xml-php/
<?php
header('Access-Control-Allow-Origin: *');
$oid= $_GET['oid'];
//database configuration
$config['mysql_host'] = "localhost";
$config['mysql_user'] = "thisisuser";
$config['mysql_pass'] = "thisispass";
$config['db_name'] = "mydb";
$config['table_name'] = "mail";
//connect to host
mysql_connect($config['mysql_host'],$config['mysql_user'],$config['mysql_pass']);
//select database
#mysql_select_db($config['db_name']) or die( "Unable to select database");
$xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
$root_element = $config['table_name']."s"; //fruits
$xml .= "<$root_element>";
//select all items in table
$sql = "SELECT * FROM mail WHERE oid='".$oid."' ORDER BY id ";
//SELECT * FROM ".$config['table_name'];
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
if(mysql_num_rows($result)>0)
{
while($result_array = mysql_fetch_assoc($result))
{
$xml .= "<".$config['table_name'].">";
//loop through each key,value pair in row
foreach($result_array as $key => $value)
{
//$key holds the table column name
$xml .= "<$key>";
//embed the SQL data in a CDATA element to avoid XML entity issues
$xml .= "$value";
//and close the element
$xml .= "</$key>";
}
$xml.="</".$config['table_name'].">";
}
}
//close the root element
$xml .= "</$root_element>";
//send the xml header to the browser
header ("Content-Type:text/xml");
//output the XML data
echo $xml;
?>
It work just fine after a few edit and the output goes like this.
<mails>
<mail>
<id>101221</id>
<oid>1</oid>
<from>Test User</from>
<content>This is a test mail.</content>
</mail>
<mail>
<id>101222</id>
<oid>1</oid>
<from>Test User</from>
<content>This is a test mail.</content>
</mail>
</mails>
My problem is Id like to display the array count next to the mail tag similar to something like
<mails>
<mail id="1"> <-fetched array number?
<id>101221</id>
<oid>1</oid>
<from>Test User</from>
<content>This is a test mail.</content>
</mail>
<mail id="2">
<id>101222</id>
<oid>1</oid>
<from>Test User</from>
<content>This is a test mail.</content>
</mail>
</mails>
Please help me.
Change this:
$xml .= "<".$config['table_name'].">";
To this:
$xml .= "<".$config['table_name']." id='".$result_array['id']."'>";
I'm trying to store a xml as string in a variable so that I can store it in my database.
$xml = "<root>";
foreach(...){
$xml .= "<user id='$id'/>";
}
$xml .= "</root>";
When I echo it, it's not displayed at all as if my web brower reads it as html tag. It doesn't even look like $xml is storing those as texts. Now, I'm trying to do it with DOMDocument... not not quite successful yet. Any tips? :(
Edited my stupid += mistakes..
PHP uses a . as a concatenate operator, or a .= as a shortcut, not a + or +=.
$xml = "<root>";
foreach(...){
$xml .= "<user id='$id'/>";
}
$xml .= "</root>";
I'm working on my php script to output the information from mysql database. I want to output these echo results in my php page as a xml file as i want to make it looks like this:
<?xml version="1.0" encoding="UTF-8" ?>
<tv generator-info-name="www.mysite.com/xmltv">
<channel id="">
<display-name></display-name>
<programme channel="" start="" stop="">
<title lang="en"></title>
<sub-title lang="en"></sub-title>
<desc lang="en"></desc>
<category lang="en"></category>
</programme>
</channel>
Here's my PHP:
<?php
function db_connect()
{
define('DB_HOST', 'localhost');
define('DB_USER', 'myusername');
define('DB_PASSWORD', 'mypasword');
define('DB_DATABASE', 'mydbname');
$errmsg_arr = array();
$errflag = false;
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link)
{
die('Failed to connect to server: ' . mysql_error());
}
$db = mysql_select_db(DB_DATABASE);
if(!$db)
{
die("Unable to select database");
}
}
db_connect();
function clean($var)
{
return mysql_real_escape_string(strip_tags($var));
}
$channels = clean($_GET['channels']);
$id = clean($_GET['id']);
if($errflag)
{
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
echo implode('<br />',$errmsg_arr);
}
else
{
$insert = array();
if(isset($_GET['channels']))
{
$insert[] = 'channels = \'' . clean($_GET['channels']) .'\'';
}
if(isset($_GET['id']))
{
$insert[] = 'id = \'' . clean($_GET['id']) . '\'';
}
if($channels && $id)
{
$qrytable1="SELECT id, channels, links FROM tvguide WHERE channels='$channels' && id='$id'";
$result1=mysql_query($qrytable1) or die('Error:<br />' . $qry . '<br />' . mysql_error());
while ($row = mysql_fetch_array($result1))
{
zap2it($row);
}
mysql_close();
}
else if(!$channels && ! $id)
{
$qrytable1="SELECT id, channels, links, streams FROM tvguide";
$result1=mysql_query($qrytable1) or die('Error:<br />' . $qry . '<br />' . mysql_error());
echo '<?xml version=""1.0"" encoding="UTF-8" ?>';
echo '<tv generator-info-name="www.mysite.com/xmltv">';
echo '<channel id="">';
echo '<display-name></display-name>';
echo '<programme channel="" start="" stop="">';
echo '<title lang="en"></title>';
echo '<sub-title lang="en"></sub-title>';
echo '<desc lang="en"></desc>';
echo '<category lang="en"></category>';
echo '</programme>';
echo '</channel>';
while ($row = mysql_fetch_array($result1))
{
echo "<p id='channels'>".$row["id"]. " " . $row["channels"]. "</p>";
echo "<p id='links'>";
echo "http://www.mysite.com/get-listing.php?channels=" . $row["channels"] . "&id=" . $row["id"] .'</p>';
}
}
}
?>
Here's what my php output looks like:
<?xml version="1.0" encoding="UTF-8" ?><tv generator-info-name="www.mysite.com/xmltv"><channel id=""><display-name></display-name><programme channel="" start="" stop=""><title lang="en"></title><sub-title lang="en"></sub-title><desc lang="en"></desc><category lang="en"></category></programme></channel>
Edit: I have got a problem with echo. I can't be able to echo for the channels in the database.
if(!$channels && ! $id)
{
$qrytable1="SELECT id, channels, links, streams FROM tvguide";
$result1=mysql_query($qrytable1) or die('Error:<br />' . $qry . '<br />' . mysql_error());
while ($row = mysql_fetch_array($result1))
{
}
mysql_close();
}
Here's the error I have got: error on line 12 at column 11: XML declaration allowed only at the start of the document
I will get the error when I'm using this under the while statement:
while ($row = mysql_fetch_array($result1))
{
echo '<?xml version="1.0" encoding="UTF-8" ?>
<tv generator-info-name="www.mysite.com/xmltv">
<channel id="">
<display-name></display-name>
<programme channel="" start="" stop="">
<title lang="en"></title>
<sub-title lang="en"></sub-title>
<desc lang="en"></desc>
<category lang="en"></category>
</programme>
</channel>
</tv>';
}
The output for my php is show as blank page. How do you use the code to allow me to print these xml output in my php?
if channel = 0 and id = 0 your output is correct. It may not be tabbed, but it is correct to your logic.
Depending on the browser XML might show a blank page ... make sure you do view code!
You need to rethink your logic though $channel && $id and then do !$channel && !id is suspiciously odd.
It looks like you are already successfully generating XML. Your problem is that it shows up as a blank page. This is expected, because your web browser is going to interpret the XML as a bunch of HTML tags, and tags don't get displayed.
What you probably want to do is set the content type to XML so that the web browser knows it's XML and not HTML. You can do this by adding the header before you send any other output (i.e. before any echo statements):
header('Content-type: application/xml');
This is necessary because if you don't specify the content type explicitly, the server will automatically send a content type header that tells the browser that the content is HTML.
You can use your browser's debugging console (press F12 to open it in most modern browsers) to inspect the HTTP headers that your script is sending and verify that it's declaring the correct content type.
The other alternative is to format the XML as HTML. This probably isn't really desirable, because the purpose of XML is the be processed by some other client and turning it into HTML makes it useless. However, if you really want to, it can be done by putting all the XML in a string and then calling the htmlspecialchars function to format it as HTML. (This turns the < and > into HTML entities, causing them to be displayed in your browser.)
I am using a drupal_http_request to an xml string from another web site I am currently trying to figure out how to grab this as an xml it does not seem to be working but when I run the exact same url in a browser it gives me back the information in xml format any ideas on how to do this Thought if I put something in like $headers = array("Content-Type: text/xml") when I execute $http_contents = drupal_http_request($url, $headers = array("Content-Type: text/xml")); it would give me the data in an xml format but it is not any ideas thanks in advance Below is my code
<form method="post">
<p>Last Name: <input type="text" name="lastname" /><br />
First Name: <input type="text" name="firstname" /></p>
<p><input type="submit" value="Send it!"></p>
</form>
<?php
if($_POST)
{
$url = "https://pdb-services-beta.nipr.com/pdb-xml-reports/hitlist_xml.cgi?customer_number=testlogin&pin_number=testpin&report_type=1";
$url = $url . "&name_last=" . $_POST['lastname'] ."&name_first=". $_POST['firstname'];
$result = grabData($url);
$xml=simplexml_load_file("$result.xml");
$nipr_id = $xml->NPN;
echo "Agent " . $_POST['firstname'] . " " . $_POST['lastname'] . " Id is:". $nipr_id . "<br />\n";
}
?>
<?php
function grabData($url)
{
$http_contents = drupal_http_request($url);
if (!isset($http_contents->data)) {
throw new RuntimeException("Cannot get contents from the URL");
}
if($replace_special_characters)
$http_contents_data = str_replace('&','&', $http_contents->data);
else
$http_contents_data = $http_contents->data;
$xml_parser = xml_parser_create();
xml_parse_into_struct($xml_parser, $http_contents_data, $result);
xml_parser_free($xml_parser);
echo "Display http_contents_data " . $http_contents_data . "<br />\n";
echo "Display result " . $result . "<br />\n";
return $result;
}
?>
here is what I am receiving
LISTsamplelastname, samplefirstname samplemiddlenamesampleidsampleidstateDOB
and when I run the url through the browser I get this
<?xml version='1.0' encoding='UTF-8'?>
<HITLIST>
<TRANSACTION_TYPE>
<TYPE>
LIST
</TYPE>
</TRANSACTION_TYPE>
<INDIVIDUAL>
<NAME>
samplelastname, samplefirstname samplemiddlename
</NAME>
<ID_ENTITY>
sampleid
</ID_ENTITY>
<NPN>
sampleid
</NPN>
<STATE_RESIDENT>
state
</STATE_RESIDENT>
<DATE_BIRTH>
dob
</DATE_BIRTH>
</INDIVIDUAL>
<INDIVIDUAL>
</INDIVIDUAL>
With the help of Supdley and My fellow worker John Salevetti I found the solution. Merely wrap the xml contents in htmlspecialchars the xml now displays
The answer to this was wrapping the xml content in question in a htmlspecialchars command this will override the suppression of non-html characters on the page. Would like to send a shoutout to Spudley who looked at this code and reminded me of the nonhtml character suppression Thanks Spudley for helping me not to go too far down that rabbit hole!
this was the original line ....
echo "Display http_contents_data " . $http_contents_data . "<br />\n";
and this is the modified line......
echo "Display http_contents_data " . htmlspecialchars($http_contents_data) . "<br />\n";
I have a problem with XML data generated by a PHP file.
here is my code:
$requestXmlBody .= "<PictureURL>";
//find black
while($row = mysql_fetch_object($ergebnis))
{
$posblack = strpos($row->image, $findBLACK);
if ($posblack !== false)
{
echo $row->image;
}
}
$requestXmlBody .= "</PictureURL>";
This code will generate the XML Code
<PictureURL></PictureURL>
but not the name I fetch from the database. The database query is working but my problem ist to have it inserted between the XML code.
Usually a variable is inserted like this
$requestXmlBody .= '<PictureURL>$variable</PictureURL>';
I just don't know how to wrap this around my database query.
Any help is very appreciated.
Something like this?
while($row = mysql_fetch_object($ergebnis)) {
$posblack = strpos($row->image, $findBLACK);
if ($posblack !== false) {
$requestXmlBody .= "<PictureURL>";
$requestXmlBody .= $row->image;
$requestXmlBody .= "</PictureURL>";
}
}
You are echo'ing $row->image instead of appending to $requestXmlBody
Change your code to:
$requestXmlBody .= $row->image;