dynamic xml using php - php

i have an xml file. how to make dynamic xml?
<?xml version="1.0" encoding="ISO-8859-1"?>
<jukebox>
<song title="When the Levee Breaks" artist="Kansas Joe and Memphis Minnie" url="songs/levee.mp3" />
<song title="Better Leave that Stuff Alone" artist="Will Shade" url="songs/alone.mp3" />
<song title="Walk Right In" artist="Cannon's Jug Stompers" url="songs/walk.mp3" />
</jukebox>
here i have to fetch files from database. how it is possible?

I quite don't understand if you want to pull out those information from MySQL to XML or XML to HTML...
In the first case, we'll need more informations like :
Your MySQL schema
How do you extract info from there now
What did you try so far
In the second case, you can use that code :
<?php
$xml = '<?xml version="1.0" encoding="ISO-8859-1"?>
<jukebox>
<song title="When the Levee Breaks" artist="Kansas Joe and Memphis Minnie" url="songs/levee.mp3" />
<song title="Better Leave that Stuff Alone" artist="Will Shade" url="songs/alone.mp3" />
<song title="Walk Right In" artist="Cannon\'s Jug Stompers" url="songs/walk.mp3" />
</jukebox>';
$doc = new DOMDocument;
$doc->loadXML($xml);
$songs = $doc->getElementsByTagName('song');
foreach($songs as $song){
echo ''.$song->getAttribute('title').' by '.$song->getAttribute('artist').'';
}
DEMO HERE

It would depend on a number of other factors you haven't elaborated on, however given you intend on generating the file with PHP, and you've sorted out your database logic, something like this would work:
<?php foreach($songs as $song): ?>
<song title="<?php echo $song['title']; ?>"
artist="<?php echo $song['artist']; ?>"
url="<?php echo $song['url']; ?>" />
<?php endforeach; ?>
More details are really necessary to give you any more of answer though. For example, language?

Related

Using xpath to query XML in PHP

I am using xpath for the first time to query an xml document for a value and return the corresponding name value. I have been reading numerous different sources on the topic but I can't seem to get it to output correctly. Here is my XML:
<?xml version="1.0" encoding="utf-8"?>
<books>
<book>
<name>Genesis</name>
<abrv>GEN</abrv>
<title>The First Book of Moses</title>
</book>
<book>
<name>Exodus</name>
<abrv>EXO</abrv>
<title>The Second Book of Moses</title>
</book>
<book>
<name>Leviticus</name>
<abrv>LEV</abrv>
<title>The Third Book of Moses</title>
</book>
</books>
Here is my PHP/HTML:
<?php $root = $_SERVER['DOCUMENT_ROOT'] . "/";
$bookID = 'GEN';
$xml = simplexml_load_file( $root . 'assets/xml/books.xml' ) or die( "No Page Data Found" );
$bookName = $xml->xpath( '//book[abrv="'.$bookID.'"]/name' );
?>
<article id="verseOfDay">
<div class="container">
<h2>verse of the day</h2>
<h6><?php echo $bookName; ?></h6> // Line 19
<p></p>
</div>
</article>
Finally, here is the notice that I am receiving:
NOTICE: ARRAY TO STRING CONVERSION IN /HOME/#####/MYWEBSITE.COM/ASSETS/INCLUDES/VERSEOFTHEDAY.PHP ON LINE 19
ARRAY
What am I doing wrong? In this example I am expecting it to output Genesis in the tag.
The SimpleXML xpath function returns an array of results, which will be empty if no result is found. So you need to check for that, and if you get a result, it will be at $bookName[0]. Something like this will work:
$bookNames = $xml->xpath( '//book[abrv="'.$bookID.'"]/name' );
$bookName = empty($bookNames) ? 'Not Found' : $bookNames[0];
?>
<article id="verseOfDay">
<div class="container">
<h2>verse of the day</h2>
<h6><?php echo $bookName; ?></h6>
<p></p>
</div>
</article>
Demo on 3v4l.org

Looping through multiple images in xml file with php code

Below is my PHP code and XML file, I have been trying with so many different echos to loop through my images in my XML file to display each image to correct product but can only display the first image to all three products.
XML code:
<my_products>
<product>
<id>1</id>
<image> csuT.jpg</image>
<name>Champion T-Shirt</name>
<price>18.00</price>
<description>
Get the perfect look to let everyone know you are a stylish fan!
</description>
</product>
<product>
<id>2</id>
<image> webBook.jpg</image>
<name>C# Programming: Analysis to Program Design</name>
<price>192.00</price>
<description>
Your hands-on guide to Microsoft Visual C# fundamentals with Visual Studio 2017
</description>
</product>
<product>
<id>3</id>
<image> calcPic.jpg</image>
<name>Calculator TI-BAII Plus 10DIG/24CASH</name>
<price>39.00</price>
<description>
Performs common math as well as various financial functions
</description>
</product>
</my_products>
PHP code:
$xml = simplexml_load_file($file);
$script_images="";
$script_products="";
$script_product_prices="";
//Loop through the products defined in the products.xml file
foreach ($xml->product as $r)
{
$script_images.="products[".($r->id)."]=\"".($r->image)."\";\n";
$script_products.="products[".($r->id)."]=\"".($r->name)."\";\n";
$script_product_prices.="product_prices[".($r->id)."]=\"".($r->price)."\";\n";
?>
<div>
<p class="lead">
<h3 class="pull-right no-top-margin"><?php echo $currency_symbol;?><?php echo $r->price;?></h3>
<h3><?php echo "<image src='csuT.jpg' 'calcPic.jpg' 'webBook.jpg'/>";?></h3>
</p>
<h3><?php echo $r->name;?></h3>
</p>
<p>
<?php echo $r->description;?>
</p>
<br/>
<?php
//If there is details link set for the product, show a Details button
if(trim($r->details_link)!="")
{
?>
<a target="_blank" href="http://<?php echo str_replace("http://","",trim($r->details_link));?>"</a>
<?php
}
?>
<a class="btn btn-xs btn-info" href="javascript:AddToCart(<?php echo $r->id;?>)">Add to Cart</a>
</div>
<hr/>
<?php
}
?>
<script>
var currency_symbol="<?php echo $currency_symbol;?>";
var products=Array();
<?php echo $script_images;?>
var product_images=Array();
<?php echo $script_products;?>
var product_prices=Array();
<?php echo $script_product_prices;?>
</script>
You just need to extract the image from the XML (the same way as done for the Javascript) and I've added a trim() to remove any spaces round the field...
<h3><?php $image = trim($r->image);
echo "<image src='$image'/>";?></h3>
Also add trim to...
$script_products.="products[".($r->id)."]=\"".($r->name)."\";\n";
What is this? :
<h3><?php echo "<image src='csuT.jpg' 'calcPic.jpg' 'webBook.jpg'/>";?></h3>
your src attribute is static and you must change it

Regex - Replacing content - eZ Publish XML field

I have an Xml content that i want to modify before using the eZ Publish 5 API to create it.
I am trying to implement a Regex to modify the content.
Here is the Xml code that i have (with html entities) :
Print of Xml code http://img15.hostingpics.net/pics/453268xmlcode.jpg
I want to be able to catch empty.jpg in :
<img alt="" src="http://www.asite.org/empty.jpg" />
And replace the whole line for each occurrence by :
<custom name="my_checkbox"></custom>
Problem :
The img tag can sometimes contain other attributes like : height="15" width="12"
<img height="15" alt="" width="12" src="http://www.asite.org/empty.jpg" />
And sometimes the attributes are after the src attribute in a different order.
The aim would be :
Xml code - Aim http://img15.hostingpics.net/pics/318980xmlcodeaim.jpg
I've tried many things so far but nothing worked.
Thanks in advance for helping.
Cheers !
EDIT :
Here is an example of what i've tried so far :
/(<img [a-z = ""]* src="http:\/\/www\.asite\.org\/empty\.jpg" \/&gt)/g
Dealing with XML i've used an XML parser to reach the desired section.
Then we can apply a regex (~<img.*?>(?=</span)~) to select and replace the image tag with your custom tag (note that in the object received by the xml parser the html entities are replaces with their equivalent char).
This is a piece of code that emulates and handle your situation:
<?php
$xmlstr = <<<XML
<sections>
<section>
<paragraph>
<literal class="html">
<img alt="" src="http://asite.org/empty.png" /></span></span> Yes/no&nbsp;<br />
<img alt="" src="http://asite.org/empty.png" /></span></span> Other text/no&nbsp;<br />
</literal>
</paragraph>
</section>
</sections>
XML;
$sections = new SimpleXMLElement($xmlstr);
foreach ($sections->section->paragraph as $paragraph) {
$re = "~<img.*?>(?=</span)~";
$subst = "<custom name=\"my_checkbox\"></custom>";
$paragraph->literal = preg_replace($re, $subst, $paragraph->literal);
}
echo $sections->asXML();
?>
The output is:
<?xml version="1.0"?>
<sections>
<section>
<paragraph>
<literal class="html">
<custom name="my_checkbox"></custom></span></span> Yes/no&nbsp;<br />
<custom name="my_checkbox"></custom></span></span> Other text/no&nbsp;<br />
</literal>
</paragraph>
</section>
</sections>
An online demo can be found HERE

XML to MySQL when xml file has multiple matching fields

I've been doing some work on an XML to Mysql using load XML. I have been successful with itin the past. The difference with the latest effort is that we have multiple occurrences of a field-name in the MySQL. A sample of this is below:
<row>
<pictures>
<picture name="Photo 1">
<filename>image1.jpg</filename>
</picture>
<picture name="Photo 2">
<filename>image2.jpg</filename>
</picture>
<picture name="Photo 4">
<filename>image3.jpg</filename>
</picture>
<picture name="Photo 3">
<filename>image4.jpg</filename>
</picture>
<picture name="Photo 7">
<filename>image5.jpg</filename>
</picture>
<picture name="Photo 6">
<filename>image6.jpg</filename>
</picture>
<picture name="Photo 5">
<filename>image7.jpg</filename>
</picture>
<picture name="Photo 8">
<filename>image8.jpg</filename>
</picture>
<picture name="Photo 9">
<filename>image9.jpg</filename>
</picture>
</pictures>
</row>
I need to import this into a MySQL table with the fields:
picture1
picture2
picture3
picture4
picture5
picture6
picture7
picture8
picture9
As you can see, the 'name' attribute doesn't necessarily occur in the correct order, so I need them to simply be inserted in order. So the first <filename> to go to picture1, the second <filename> to picture2 etc..
What is currently being achieved is that I always end up with the last <picture> entry in the list being in the table. This is I assume because the filed is being overwritten each time.
Any ideas how to achieve this? I have found similar queries to this but no answers as yet and have been looking for a good while. The rest of the file is loading fine as they have unique field-names and can easily be mapped to a MySQL column, but I am struggling with this one.
As the XML does not match the format you aim for you need to transform it first. Traditionally this is done with XSLT but you can also do this with XMLReader and XMLWriter in PHP which has the benefit that it does not require to keep the whole XML document(s) in memory.
The XMLReaderIterator package has support for such operations, an example is already given with the library.
Creating a modification of that example code by taking your specific case and an exemplary input file named pictures.xml and keeping the output to the standard-output for demonstration purposes allows me to quote the following excerpt:
[... starts like examples/read-write.php]
/** #var $iterator XMLWritingIteration|XMLReaderNode[] */
$iterator = new XMLWritingIteration($writer, $reader);
$writer->startDocument();
$rename = ['row' => 'resultset', 'pictures' => 'row'];
$trimLevel = null;
$pictureCount = null;
foreach ($iterator as $node) {
$name = $node->name;
$isElement = $node->nodeType === XMLReader::ELEMENT;
$isEndElement = $node->nodeType === XMLReader::END_ELEMENT;
$isWhitespace = $node->nodeType === XMLReader::SIGNIFICANT_WHITESPACE;
if (($isElement || $isEndElement) && $name === 'filename') {
// drop <filename> opening and closing tags
} elseif ($isElement && $name === 'picture') {
$writer->startElement('field');
$writer->writeAttribute('name', sprintf('picture%d', ++$pictureCount));
$trimLevel = $node->depth;
} elseif ($trimLevel && $isWhitespace && $node->depth > $trimLevel) {
// drop (trim) SIGNIFICANT_WHITESPACE
} elseif ($isElement && isset($rename[$name])) {
$writer->startElement($rename[$name]);
if ($rename[$name] === 'row') {
$pictureCount = 0;
}
} else {
$iterator->write();
}
}
This is one XMLWritingIteration that is composed of an XMLReader and XMLWriter object. That iteration allows you to take over everything from the input document (via $iterator->write()) and do the needed changes only on occasions:
drop the <filename> and </filename> tags
create <field> elements with the correct name attributes to have the pictures in document order (Mysql XML nomenclature)
drop significant whitespace as <filename> tags are dropped as well
rename the document element from <row> to <resultset> (Mysql XML nomenclature)
rename the <pictures> element to <row> (again Mysql XML nomenclature)
the counter for the picture fields is reset per each (output) row
everything else is kept as-is
Such a transformation results in the following example output with the XML presented in your question:
<?xml version="1.0"?>
<resultset>
<row>
<field name="picture1">image1.jpg</field>
<field name="picture2">image2.jpg</field>
<field name="picture3">image3.jpg</field>
<field name="picture4">image4.jpg</field>
<field name="picture5">image5.jpg</field>
<field name="picture6">image6.jpg</field>
<field name="picture7">image7.jpg</field>
<field name="picture8">image8.jpg</field>
<field name="picture9">image9.jpg</field>
</row>
</resultset>
For more information about the XML format used by Mysql, please see the Mysql documentation for the --xml commandline switch which describes the standard XML output format which can be read in by LOAD XML.
For this little example you could as well use XSLT as there would be no problem to do the whole transformation in memory. But if you need to look for memory (which can happen if you deal with XML database dumps), the XMLWritingIteration allows iteration based XML transformation with an XML Pull parser (XMLReader) and forward-only XML output via XMLWriter.
And here is the XSLT solution. As information, XSLT is a declarative special-purpose language to transform, re-style, and restructure XML documents in various formats for end use purposes. PHP maintains an XSLT processor. Be sure to uncomment out extension=php_xsl.dll
XLST (accommodates image numbers greater than two digits)
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output version="1.0" encoding="UTF-8"/>
<xsl:template name="picturesort" match="pictures" >
<row>
<pictures>
<xsl:for-each select="picture">
<xsl:variable name="numkey"
select="substring-after(substring-before(filename, '.'), 'e')"/>
<picture name="{../picture[substring-after(#name, ' ') = $numkey]/#name}">
<xsl:copy-of select="filename"/>
</picture>
</xsl:for-each>
</pictures>
</row>
</xsl:template>
</xsl:stylesheet>
XML OUTPUT
<?xml version="1.0" encoding="UTF-8"?>
<row>
<pictures>
<picture name="Photo 1">
<filename>image1.jpg</filename>
</picture>
<picture name="Photo 2">
<filename>image2.jpg</filename>
</picture>
<picture name="Photo 3">
<filename>image3.jpg</filename>
</picture>
<picture name="Photo 4">
<filename>image4.jpg</filename>
</picture>
<picture name="Photo 5">
<filename>image5.jpg</filename>
</picture>
<picture name="Photo 6">
<filename>image6.jpg</filename>
</picture>
<picture name="Photo 7">
<filename>image7.jpg</filename>
</picture>
<picture name="Photo 8">
<filename>image8.jpg</filename>
</picture>
<picture name="Photo 9">
<filename>image9.jpg</filename>
</picture>
</pictures>
</row>
PHP
<?php
// Load the XML source
$xml = new DOMDocument;
$xml->load('C:/Path/To/XMLfile.xml');
$xsl = new DOMDocument;
$xsl->load('C:/Path/To/XSLfile.xsl');
// Configure the transformer
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl);
// Transform XML source
$newXml = $proc->transformToXML($xml);
echo $newXml;
// Save output to file
file_put_contents("C:/Path/To/NewXMLfile.xml", $newXml);
?>
Possible way:
iterate over all <picture> in a <row>
build an associative array with key = name and value = filename
sort array by keys
feed the array to your DB

Xpath query in PHP to attribute from element with specific attribute value

I'm truly bending my head over something that should be way to simple. I have an XML feed with 25 entries in the root. I'm already iterating them as $entry in PHP.
Here is an example of one entry in the xml feed:
<entry>
<id>tag:blogger.com,1999:blog-7691515427771054332.post-4593968385603307594</id>
<published>2014-02-10T06:33:00.000-05:00</published>
<updated>2014-02-10T06:40:34.678-05:00</updated>
<category scheme="http://www.blogger.com/atom/ns#" term="Aurin" />
<category scheme="http://www.blogger.com/atom/ns#" term="fan art" />
<category scheme="http://www.blogger.com/atom/ns#" term="Fred-H" />
<category scheme="http://www.blogger.com/atom/ns#" term="spellslinger" />
<category scheme="http://www.blogger.com/atom/ns#" term="wildstar" />
<title type="text">Fan Art Showcase: She's gunnin' for trouble!</title>
<content type="html">Some random content</content>
<link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/7691515427771054332/posts/default/4593968385603307594" />
<link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/7691515427771054332/posts/default/4593968385603307594" />
<link rel="alternate" type="text/html" href="http://www.wildstarfans.net/2014/02/fan-art-showcase-shes-gunnin-for-trouble.html" title="Fan Art Showcase: She's gunnin' for trouble!" />
<author>
<name>Name Removed</name>
<uri>URL removed</uri>
<email>noreply#blogger.com</email>
<gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="//lh3.googleusercontent.com/-ow-dvUDbNxI/AAAAAAAAAAI/AAAAAAAABTY/MhrybgagMv0/s512-c/photo.jpg" />
</author>
<media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://3.bp.blogspot.com/-Ifp6awhDJuU/UWQEUl8nhUI/AAAAAAAABss/BSZ_YYM1U38/s72-c/fan-art-header.png" height="72" width="72" />
</entry>
I want to get the href of the third link with rel set to alternate. The alternate link isn't always the third one. I know how to do this through SimpleXML, but I want to get to know xpath for this, because through simpleXML it's more complicated and with this I hope I'm one step closer to understanding complex xpath queries.
The PHP I got that makes the most sense to me is:
$href = $entry->xpath('link[#rel="alternate"]/#href');
I tried multiple queries based on the information I found, but they all resulted in nothing. Here is a list of the queries I tried:
$href = $entry->xpath('link[#rel="alternate"]/#href/text()');
$href = $entry->xpath('link[#rel="alternate"]')->getAttributes()->href;
$href = $entry->xpath('*[#rel="alternate"]'); $href = $href['href'];
As it turns out from the chat conversation from my original question I had to register the namespace. In the end I used this website and the code turned out to be like this:
$feed = new DOMDocument();
$feed->load("http://www.wildstarfans.net/feeds/posts/default");
$xpath = new DOMXPath($feed);
$xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
foreach ($xpath->evaluate('//atom:entry') as $entry) {
$href = $xpath->evaluate('string(atom:link[#rel="alternate"]/#href)', $entry);
}
Credits go to ThW and Wrikken. Wish I could give you guys SO points for this.
$href = $entry->xpath('link[#rel="alternate"]');
$href = (string) $href[0]->attributes()->href;

Categories