How to show image element from XML with php - php

I've tried what others have posted on stack overflow but it doesn't seem to work for me. So could anyone help please.
I have this xml document with a structure of:
<surveys>
<survey>
<section>
<page>
<reference>P1</reference>
<image><! [CDATA[<img src="imagepath">]]></image>
</page>
<page>
<reference>P2</reference>
<image><! [CDATA[<img src="imagepath">]]></image>
</page>
</section>
</survey>
</surveys>
Then this is my PHP code to get the image to show up:
function xml($survey){
$result = "<surveys></surveys>";
$xml_surveys = new SimpleXMLExtended($result);
$xml_survey = $xml_surveys->addChild('survey');
if ("" != $survey[id]){
$xml_survey_>addChildData($survey['image']);
}
This is my other file:
$image = “”;
if(“” != $image){
$image = <div class=“image_holder”> $image </div>
echo $image;
}
I'm not sure how to progress forward with this. so any help would be appreciated

It looks like you would like to fetch the image for a specific survey id. Well you can use DOM+Xpath To fetch this directly:
$document = new DOMDocument();
$document->loadXML($xml);
$xpath = new DOMXpath($document);
$expression = 'string(
/surveys/survey/section/page[reference="P1"]/image
)';
$imageForSurvey = $xpath->evaluate($expression);
var_dump($imageForSurvey);
Output:
string(22) "<img src="imagepath1">"
The content of the CDATA section inside the image element is a separate HTML fragment. You can use it directly if you trust the source of the XML or you parse it as HTML.
$htmlFragment = new DOMDocument();
$htmlFragment->loadHTML($imageForSurvey);
$htmlXpath= new DOMXpath($htmlFragment);
var_dump(
$htmlXpath->evaluate('string(//img/#src)')
);
Output:
string(10) "imagepath"

Your example-logic is trying to create XML, not load it ;-)
First you need to find the path and/or address to the XML file, like:
$filePath = __DIR__ . '/my-file.xml';
Then load XML:
<?php
$filePath = __DIR__ . '/my-file.xml';
$document = simplexml_load_file($filePath);
$surveyCount = 0;
foreach($document->survey as $survey)
{
$surveyCount = $surveyCount + 1;
echo '<h1>Survey #' . $surveyCount . '</h1>';
foreach($survey->section->page as $page)
{
echo 'Page reference: ' . $page->reference . '<br>';
// Decode your image.
$imageHtml = $page->image;
$dom = new DOMDocument();
$dom->loadHTML($imageHtml);
$xpath= new DOMXpath($dom);
$image = $xpath->evaluate('string(//img/#src)');
if(!empty($image)) {
echo '<div class=“image_holder”>' . $image . '</div>';
}
echo "<br>";
}
}
?>
Note that you should replace <! [CDATA[ with <![CDATA[ (without space),
else you will get StartTag: invalid element name error probably.

Related

Retrieve data from html page using xpath and php

I know there are similar question, but, trying to study PHP I met this error and I want understand why this occurs.
<?php
$url = 'http://aice.anie.it/quotazione-lme-rame/';
echo "hello!\r\n";
$html = new DOMDocument();
#$html->loadHTML($url);
$xpath = new DOMXPath($html);
$nodelist = $xpath->query(".//*[#id='table33']/tbody/tr[2]/td[3]/b");
foreach ($nodelist as $n) {
echo $n->nodeValue . "\n";
}
?>
this prints just "hello!". I want to print the value extracted with the xpath, but the last echo doesn't do anything.
You have some errors in your code :
You try to get the table from the url http://aice.anie.it/quotazione-lme-rame/, but it's actually in an iframe located at http://www.aiceweb.it/it/frame_rame.asp, so get the iframe url directly.
You use the function loadHTML(), which load an HTML string. What you need is the loadHTMLFile function, which takes the link of an HTML document as a parameter (See http://www.php.net/manual/fr/domdocument.loadhtmlfile.php)
You assume there is a tbody element on the page but there is no one. So remove that from your query filter.
Working code :
$url = 'http://www.aiceweb.it/it/frame_rame.asp';
echo "hello!\r\n";
$html = new DOMDocument();
#$html->loadHTMLFile($url);
$xpath = new DOMXPath($html);
$nodelist = $xpath->query(".//*[#id='table33']/tr[2]/td[3]/b");
foreach ($nodelist as $n) {
echo $n->nodeValue . "\n";
}

DOMDocument grab html between two p tags [duplicate]

I'm trying to replace video links inside a string - here's my code:
$doc = new DOMDocument();
$doc->loadHTML($content);
foreach ($doc->getElementsByTagName("a") as $link)
{
$url = $link->getAttribute("href");
if(strpos($url, ".flv"))
{
echo $link->outerHTML();
}
}
Unfortunately, outerHTML doesn't work when I'm trying to get the html code for the full hyperlink like <a href='http://www.myurl.com/video.flv'></a>
Any ideas how to achieve this?
As of PHP 5.3.6 you can pass a node to saveHtml, e.g.
$domDocument->saveHtml($nodeToGetTheOuterHtmlFrom);
Previous versions of PHP did not implement that possibility. You'd have to use saveXml(), but that would create XML compliant markup. In the case of an <a> element, that shouldn't be an issue though.
See http://blog.gordon-oheim.biz/2011-03-17-The-DOM-Goodie-in-PHP-5.3.6/
You can find a couple of propositions in the users notes of the DOM section of the PHP Manual.
For example, here's one posted by xwisdom :
<?php
// code taken from the Raxan PDI framework
// returns the html content of an element
protected function nodeContent($n, $outer=false) {
$d = new DOMDocument('1.0');
$b = $d->importNode($n->cloneNode(true),true);
$d->appendChild($b); $h = $d->saveHTML();
// remove outter tags
if (!$outer) $h = substr($h,strpos($h,'>')+1,-(strlen($n->nodeName)+4));
return $h;
}
?>
The best possible solution is to define your own function which will return you outerhtml:
function outerHTML($e) {
$doc = new DOMDocument();
$doc->appendChild($doc->importNode($e, true));
return $doc->saveHTML();
}
than you can use in your code
echo outerHTML($link);
Rename a file with href to links.html or links.html to say google.com/fly.html that has flv in it or change flv to wmv etc you want href from if there are other href
it will pick them up as well
<?php
$contents = file_get_contents("links.html");
$domdoc = new DOMDocument();
$domdoc->preservewhitespaces=“false”;
$domdoc->loadHTML($contents);
$xpath = new DOMXpath($domdoc);
$query = '//#href';
$nodeList = $xpath->query($query);
foreach ($nodeList as $node){
if(strpos($node->nodeValue, ".flv")){
$linksList = $node->nodeValue;
$htmlAnchor = new DOMElement("a", $linksList);
$htmlURL = new DOMAttr("href", $linksList);
$domdoc->appendChild($htmlAnchor);
$htmlAnchor->appendChild($htmlURL);
$domdoc->saveHTML();
echo ("<a href='". $node->nodeValue. "'>". $node->nodeValue. "</a><br />");
}
}
echo("done");
?>

DomXPath with DOMDocument to get <img> Class URL

I am writing a little scraper script that will find the image URL that has a particular class name. I know that my cURL and DOMDocument is functioning okay, and even the DomXPath really (as far as I can tell, there are no errors) But I am struggling to work out how to get the URL of the xpath query results.
My code so far:
$dom = new DOMDocument();
#$dom->loadHTML($x);
$xpath = new DomXpath($dom);
$div = $xpath->query('//*[#class="productImage"]');
var_dump($div);
echo $div->item(0);
If I var_dump($x) the page outputs no problem. So the CURL is working fine. But I do not know how to get the data that is contained in the $div. I am trying to find an Image with a class of 'productImage' which looks like:
<img src="/uploads/5W/yP/5WyPP4l7Z-jmZRzu_MJ6zg/1077-d.jpg" border="1" alt="Album" class="productImage">
I want the source of that image tag.
Any suggestions?
$dom = new DOMDocument();
$dom->loadHTML($x);
$xpath = new DomXpath($dom);
$imgs = $xpath->query('//*[#class="productImage"]');
foreach($imgs as $img)
{
echo 'ImgSrc: ' . $img->getAttribute('src') .'<br />' . PHP_EOL;
}
Try that...
== EDIT: Additional Info ==
The reason I use a loop here is because you may find more than one img. If you know there is only one element (or you want the first dom node found) you can access the elelement from the domnodelist via the item method of domnodelist - like so:
$dom = new DOMDocument();
$dom->loadHTML($x);
$xpath = new DomXpath($dom);
$img = $xpath->query('//*[#class="productImage"]');
echo 'ImgSrc: ' . $img->item(0)->getAttribute('src') .'<br />' . PHP_EOL;
You don't actually need to use XPath here, because it seems that you're just after images and that can be done by using DOMDocument::getElementsByTagName(), followed by a simple filter:
foreach ($dom->getElementsByTagName('img') as $image) {
$class = $image->getAttribute('class');
if (strpos(" $class ", " productImage ") !== false) {
$url = $image->getAttribute('src');
// do stuff
}
}
Then, you can get the src attribute by using DOMElement::getAttribute():
echo $image->getAttribute('src');

How to retrieve an attribute using getElementsByTagNameNS in php?

I want to pull the news feed from "http://rapfix.mtv.com/feed" for a website that I'm creating. I have everything working other than, being able to pull the URL location of the image for each article.
In this feed, the image URL is showing up like this in the code:
<media:content url="http://rapfix.mtv.com/wp-content/uploads/2011/05/tyler-handcuff.jpg" type="image/jpeg" height="300" width="575">
<media:text type="plain"><![CDATA[tyler-handcuff]]></media:text>
</media:content>
I've read from another stackoverflow question, that you're able to pull information from the node using something like this:
$item_pic = $article->getElementsByTagNameNS('http://purl.org/rss/1.0/modules/content/', 'content')->item(0);
But now, I'm trying to get the "URL" attribute out of it. Here's a look of my code:
$xml=("http://rapfix.mtv.com/feed");
$xmlDoc = new DOMDocument();
$xmlDoc->load($xml);
$x = $xmlDoc->getElementsByTagName('item');
foreach($x as $article){
$item_title = $article->getElementsByTagName('title')->item(0)->nodeValue;
$item_link = $article->getElementsByTagName('link')->item(0)->nodeValue;
$item_desc = $article->getElementsByTagName('description')->item(0)->nodeValue;
$item_pic = $article->getElementsByTagNameNS('http://purl.org/rss/1.0/modules/content/', 'content')->item(0);
echo ("<strong><a href='".$item_link."' target='_blank'>".$item_title."</a></strong><br />");
echo ("<div><div class='FloatLeft'><img src='".$item_pic."' width='100' height='100'/></div><div class='FloatLeft'>".$item_desc." - <a href='".$item_link."' target='_blank'>Read More</a></div>^");
}
Any ideas on how to get this done?
The namespace for your target element is media. The element name is content. The Namespace URL for the media namespace is http://search.yahoo.com/mrss/. Thus:
foreach($x as $article)
{
$nlContent = $article->getElementsByTagNameNS('http://search.yahoo.com/mrss/', 'content');
if( $nlContent->length > 0 )
$item_pic = $nlContent->item(0)->getAttribute('url');
else
$item_pic = '/images/noimageavailable.jpg';
echo $item_pic . "\n";
}

How to send an email with inline images using zend framework?

The documentation specifies how to add inline attachement, but what is the correct way of referencing it from the html part? Is it possible to include images automatically as it is in other libraries?
Maybe someone has written a little snippet and is willing to share?
That's not exactly a trivial thing, lucky for you someone has subclassed Zend_Mail (Demo_Zend_Mail_InlineImages) to do that, see here:
http://davidnussio.wordpress.com/2008/09/21/inline-images-into-html-email-with-zend-framework/
i write wrapper for mail class
private function _processHtmlBody($I_html, $I_mailer, $I_data) {
$html = $I_html;
$mail = $I_mailer;
$xmlBody = new DomDocument();
$xmlBody->loadHTML($html);
$imgs = $xmlBody->getElementsByTagName('img');
$I_data['atts'] = array();
$imgCount = 0;
foreach ($imgs as $img) {
$imgCount++;
$imgUrlRel = $img->getAttribute('src');
$imgId = sha1(time() . $imgCount . $imgUrlRel);
$html = str_replace($imgUrlRel, 'cid:' . $imgId, $html);
$imgUrlFull = 'http://' . $_SERVER['HTTP_HOST'] . $imgUrlRel;
$imgBinary = file_get_contents($imgUrlFull);
$imgPart = $mail->createAttachment($imgBinary);
$imgPart->filename = 'image' . $imgCount . '.jpg';
$imgPart->id = $imgId;
$I_data['atts'][] = $imgPart;
}
$mail->setBodyHtml($html);
return $html;
}
Instead of extending Zend_Mail you can directly embed your image in base64 using html.
Here is an example image that I included in my email template:
<img src="data:image/jpg;base64,<?= base64_encode(file_get_contents("/local/path/to/image.png")) ?>" />

Categories