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" \/>)/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 <br />
<img alt="" src="http://asite.org/empty.png" /></span></span> Other text/no <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 <br />
<custom name="my_checkbox"></custom></span></span> Other text/no <br />
</literal>
</paragraph>
</section>
</sections>
An online demo can be found HERE
Related
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
Hi I am trying to wrap images containing a specific class (pinthis is this example) in a span to which I will add info for schema. This is a basic example and I will need to inject other schema info also. To get me started though can anyone help me get from my existing code to my example output. I need to update multiple pages dynamically and some of the content will come via PHP from Wordpress taxonomies and other data so would prefer to do it in PHP if possible.
<p>
<a class="fancybox" rel="gallery1" href="image.jpg">
<img src="img.jpg" alt="alt text" width="1000" height="1000" class="various classes including ... pinthis">
</a>
</p>
Which I would like to become...
<p>
<a class="fancybox" rel="gallery1" href="image.jpg">
<span itemscope itemtype="http://schema.org/ImageObject">
<img src="img.jpg" alt="alt text" width="1000" height="1000" class="various classes including ... pinthis">
</span>
</a>
</p>
I think if someone could point me in the right direction and give me a push start that would give me enough to carry on from there
Many thanks.
Using PHP DOMDocument, you could do something like this:
$html = '<p><a class="fancybox" rel="gallery1" href="image.jpg"><img src="img.jpg" alt="alt text" width="1000" height="1000" class="various classes pinthis"></a></p>';
// Create a DOMDocument and load the HTML.
$dom = new DOMDocument();
$dom->loadHTML($html);
// Create the span wrapper.
$span = $dom->createElement('span');
$span->setAttribute('itemscope', '');
$span->setAttribute('itemtype', 'http://schema.org/ImageObject');
// Get all the images.
$images = $dom->getElementsByTagName('img');
// Loop the images.
foreach ($images as $image) {
// Only affect those with the pinthis class.
if (strpos($image->getAttribute('class'), 'pinthis') !== false) {
// Clone the span if we need to use it often.
$span_clone = $span->cloneNode();
// Replace the image tag with the span tag.
$image->parentNode->replaceChild($span_clone, $image);
// Add the image tag as a child of the new span tag.
$span_clone->appendChild($image);
}
}
// Get your HTML with saveHTML()
$html = $dom->saveHTML();
echo $html;
Just modify the code to suit your specific needs. For example, if you need to change your span tag attributes, if you are changing your class for searching, etc... You might even want to make a function where you can specify your class and span attributes.
Documentation to DOMDocument: http://php.net/manual/en/class.domdocument.php
use warpAll
check if the image has required class
if image has class, then wrap it with the desired <span></span>
Try it this way :
if ($('img.classes').hasClass('pinthis')){
$('img.classes').wrapAll('<span itemscope itemtype="http://schema.org/ImageObject">></span>');
}
Fiddle Demo
helpful thread : jquery, wrap elements inside a div
I've a complex XML that I want to transform in HTML. Some tags need to be replaced in html tags.
The XML is this:
<root>
<div>
<p>
<em>bol text</em>, some normale text
</p>
</div>
<list>
<listitem>
normal text inside list <em>bold inside list</em>
</listitem>
<listitem>
another text in list...
</listitem>
</list>
<p>
A sample paragraph
</p>
The text inside the element is variable, which means that the other xml that I parse can completely change.
The output I want is this (for this scenario):
<root>
<div>
<p>
<strong>bol text</strong>, some normale text
</p>
</div>
<ul>
<li>
normal text inside list <strong>bold inside list</strong>
</li>
<li>
another text in list...
</li>
</ul>
<p>
A sample paragraph
</p>
</root>
I make a recursive function for parse any single node of xml and replace it in HTML tag (but doesn't work):
$doc = new DOMDocument();
$doc->preserveWhiteSpace = false;
$doc->load('section.xml');
echo $doc->saveHTML();
function printHtml(DOMNode $node)
{
if ($node->hasChildNodes())
{
foreach ($node->childNodes as $child)
{
printHtml($child);
}
}
if ($node->nodeName == 'em')
{
$newNode = $node->ownerDocument->createElement('strong', $node->nodeValue);
$node->parentNode->replaceChild($newNode, $node);
}
if ($node->nodeName == 'listitem')
{
$newNode = $node->ownerDocument->createElement('li', $node->nodeValue);
$node->parentNode->replaceChild($newNode, $node);
}
}
Can anyone help me?
This is an example of a complete xml:
<root>
<div>
<p>
<em>bol text</em>, some normale text
</p>
</div>
<list>
<listitem>
normal text inside list <em>bold inside list</em>
</listitem>
<listitem>
another text in list...
</listitem>
</list>
<media>
<info isVisible="false">
<title>
<p>Image title <em>in bold</em> not in bold</p>
</title>
</info>
<file isVisible="true">
<href>
"path/to/file.jpg"
</href>
</file>
</media>
<p>
A sample paragraph
</p>
</root>
Which has to be transformed into:
<root>
<div>
<p>
<strong>bol text</strong>, some normale text
</p>
</div>
<ul>
<li>
normal text inside list <em>bold inside list</em>
</li>
<li>
another text in list...
</li>
</ul>
<!-- the media tag can be presented in two mode: with title visible, and title hidden -->
<!-- this is the case when the title is hidden -->
<img src="path/to/file.jpg" />
<!-- this is the case when the title is visible -->
<!-- the info tag (inside media tag) has an attribute isVisible="false" which means it doesn't have to be shown. -->
<!-- if the info tag has visible=true, the media tag must be translated into
<div>
<img src="path/to/file.jpg" />
<p>Image title <strong>in bold</strong> not in bold</p>
<div>
-->
<p>
A sample paragraph
</p>
</root>
There's a language specially designed for this task: it's called XSLT, and you can easily express your desired transformation in XSLT and invoke it from your PHP program. There's a learning curve, of course, but it's a much better solution than writing low-level DOM code.
In XSLT you write a set of template rules saying how individual elements should be handled. Many elements in your example are copied through unchanged, so you can start with a default rule that does this:
<xsl:template match="*">
<xsl:copy><xsl:apply-templates/></xsl:copy>
</xsl:template>
The "match" part says what part of the input you are matching; the body of the rule says what output to produce. The xsl:apply-templates does a recursive descent to process the children of the current element.
Some of your elements are simply renamed, for example
<xsl:template match="listitem">
<li><xsl:apply-templates/></li>
</xsl:template>
Some of the rules are a little bit more complex, but still easily expressed:
<xsl:tempate match="media/file[#isVisible='true']">
<img src="{href}"/>
</xsl:template>
I hope you agree that this declarative rule-based approach is much clearer than your procedural code; it's also much easier for someone else to change the rules in six months' time.
Well, maybe, it's not the most correct idea, but why not just to use str_replace? That way You will see clearly the list of changes to apply and add / remove new ones easily.
file_get_contents $file = file_get_contents('file.xml');
str_replace $file = str_replace("<em>", "<strong>", $file);
file_put_contents file_put_contents('file.html', $file);
UPDATE (Some more ideas regarding the changes in the question)
This seems a little bit tricky (at least for me now) to use PHP + DOM here. Maybe, it would be more reasonable to use XSL / XSLT (Extensible Stylesheet Language Transformations). In that case, smth. similar can be found here: How to replace a node-name with another in Xslt?
XSLT specifically used for Language Transformations http://en.wikipedia.org/wiki/XSLT
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?
I need your assistence related php. In php, i want to allow html <img> tags only, i tried php's built-in function strip_tags() but it's not giving me the output i need. For instance, in the following code strip_tags() allows img tags but along with text.
$img = "<img src='/img/fawaz.jpg' alt= ''> <br /> <p> This is a detailed paragraph about Fawaz and his mates.</p>";
echo strip_tags($img , "<img>");
What would be the proper way to just allow <img> or any tag only from the function or variable.
Any help 'd be appreciated.
Thanks
This might be due to non closing img tag in your code. Try this
$img = "<img src='/img/fawaz.jpg' alt= '' /> <br /> <p> This is a detailed paragraph about Fawaz and his mates.</p>";
echo strip_tags($img , "<img>");
strip_tags() doesn't work that way you want it to behave. If supplied with a second argument, the tags listed are allowed to be part of the resulting string - except those which are not listed. And it will not filter out inner text.
If you want to extract <img/> elements only, don't even think about using a regex. Use a DOM parser for that:
libxml_use_internal_errors(true);
$doc=new DOMDocument;
$html=$doc->loadHTML('<img src="/img/fawaz.jpg" alt= ""> <br /> <p> This is a
detailed paragraph about Fawaz and his mates.</p>');
$path=new DOMXPath($doc);
foreach ($path->query('//img') as $found)
var_dump($doc->saveXML($found));
delete HTML Tags Without <img> and <a> and <br/> and <hr/> and ...
$img = "
<img src='/img/fawaz.jpg' alt= '' />
<br /><br/>
<hr/>
<p> This is a detailed paragraph about Fawaz and his mates.</p>
<a href='cft'>123</a>
";
$img = strip_tags($img , "<img>|<a>|<br>|<hr>");
echo $img;