Yii2 render xml for sitemap - yii2

I'm trying to create a sitemap for my web so I create an action to render a sitemap in format xml but i get a plain text file
My action :
public function actionIndex()
{
$channels = Channel::find()->all();
$response = Yii::$app->response;
$response->format = \yii\web\Response::FORMAT_XML;
$headers = Yii::$app->response->headers;
$headers->add('Content-Type', 'application/xml');
return $this->renderPartial('/sitemap/_viewChannel', [
'channels' => $channels,
]);
}
My view :
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
<?php foreach ($channels as $channel){ ?>
<url>
<loc><?=Url::to(['/chn-channel/view', 't'=>$channel->channel_uid])?></loc>
<changefreq>daily</changefreq>
</url>
<?php } ?>
</urlset>
but I get a normal plain text as output
Output :

You're missing XML declaration at the beginning of your XML:
<?xml version="1.0" encoding="UTF-8"?>
But XML is a plain text, it just uses specified markup and rules - the way how browser formats this output is in fact irrelevant. You need to use some sitemap validator (for example https://www.xml-sitemaps.com/validate-xml-sitemap.html or https://www.google.com/webmasters/tools/sitemap-list) to check if there are any issues with your sitemap.

Find solution by changing :
$response = Yii::$app->response;
$response->format = \yii\web\Response::FORMAT_XML;
$headers = Yii::$app->response->headers;
$headers->add('Content-Type', 'application/xml');
to
Yii::$app->response->format = \yii\web\Response::FORMAT_RAW;
Yii::$app->response->headers->add('Content-Type', 'text/xml');

Related

Laravel-generated email not formatting HTML correctly

I am struggling with email formatting issue, with Laravel.
I get the email content (HTML) from the database, which doesn't really matter, but then quotes get added around, the format is wrong and my email looks like this:
Here is my code, thanks a lot for your help!
I tried with
'content' => htmlspecialchars($content)
and
'content' => htmlentities($content)
but none work, and for the blade file:
<div>
{{!!$content!!}}
</div>
gives me an error. I also tried
<div>
{{{$content}}}
</div>
(also an error of unexpected character) and
<div>
{{$content}}
</div>
(here was the original one)
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cookie;
class InsuranceEmail extends Mailable
{
use Queueable, SerializesModels;
protected $attacheddoc;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($attacheddoc)
{
$this->attacheddoc=$attacheddoc;
}
/**
* Build the message.rubr
*
* #return $this
*/
public function build()
{
$name = Auth::user()->nom . " " . Auth::user()->prenom;
$sqlContent="SELECT texte from blabla";
$content = DB::connection('blabla')->select( DB::connection('blabla')->raw($sqlContent))[0]->texte;
$content = str_replace('#memberName#', $name, $content);
$content = str_replace('"', '', $content); //I tried this, without any hope ;)
return $this->from('contact#blabla.net')
->markdown('emails.blabla')->with([
'title' => "Email onject",
'memberName' => $name,
'content' => $content,
])
->attach($this->attacheddoc, array(
'as' => 'attacheddoc.pdf',
'mime' => 'application/pdf'));
}
}
I tried a few things to try and fix my email displaying incorrectly. In the end clearing my view cache solved my problem, which I hadn't seen anyone else suggest. This most likely wasn't your issue here but I will include it in my answer to hopefully help anyone else with my issue.
Publish the Laravel email views
php artisan vendor:publish --tag=laravel-mail
Make sure there are no indents in your html views
resources/views/vendor/mail/html
Make sure to escape any html inserted via variable
{!! $content !!}
Clear cached views
php artisan view:clear
As per Laravel Documentation:
By default, Blade {{ }} statements are automatically sent through
PHP's htmlspecialchars function to prevent XSS attacks. If you do not
want your data to be escaped, you may use the following syntax:
Hello, {!! $name !!}.
Reference:
Laravel -> Blade Templates -> Displaying Unescaped Data
In your emails.blabla view us elike this it will escape HTML element
{{{ $content }}}
or try
{!! $content !!}

Laravel 5 XML Parsing

I have created a storelocator.php in my view with the following code :
<?php
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
header("Content-type: text/xml");
foreach ($results as $value) { // ADD TO XML DOCUMENT NODE
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("name",$value->dealer_name);
$newnode->setAttribute("address", $value->address);
$newnode->setAttribute("lat", $value->lat);
$newnode->setAttribute("lng", $value->lng);
$newnode->setAttribute("type", $value->outlet_type);
}
echo $dom->saveXML();
?>
My Route is:
Route::get('/storelocator','SearchController#showReviews');
my ShowReviews Function
public function showReviews() {
//$dealer_address = dealer_addresss::lists('dealer_name','address','lat','lng','outlet_type');
//return view('/reviews',compact('dealer_address'));
$results = DB::table('dealer_address')->get();
//return view('/reviewresults',compact('results'));
return view('/storelocator',compact('results'));
}
All I get is a blank page:
When I click on source I am able to the xml content with the data but on hover it says
Attempt to use an XML processing instruction in HTML.
What am I doing wrong here ? Any guide would be immensely appreciated.
I have used this:
https://github.com/SoapBox/laravel-formatter
to make proper XML.
You probably have an error in your xml file.
Also, sending header in view is already too late.
Send it in your controller.
Related: How to make Laravel return a View's "Content-Type" header as "application/javascript"?

laravel json to xml

I need to convert json format to xml using laravel.
I'm expecting output like following.
<MESSAGE>
<AUTHKEY>Your auth key</AUTHKEY>
<SENDER>SenderID</SENDER>
<ROUTE>Template</ROUTE>
<CAMPAIGN>campaign name</CAMPAIGN>
<COUNTRY>country code</COUNTRY>
<SMS TEXT="message1">
<ADDRESS TO="number1"></ADDRESS>
</SMS>
</MESSAGE>
The array I tried to convert is,
$TEXT="HI MANI";
$MESSAGE=array("AUTHKEY"=>"68252AGguI2SK45395d8f7",
"ROUTE"=>"4","CAMPAIGN"=>"TEST",
"SENDER"=>"OODOOP","SMS"=>array("TEXT"=>$TEXT,"ADDRESS"=>array("-TO"=>"8870300358")));
$json=array("MESSAGE"=>$MESSAGE);
$jsn=json_encode($json);
This xml output json to xml:
<?xml version="1.0" encoding="utf-8"?>
<xml>
<MESSAGE>
<AUTHKEY>68252AGguI2SK45395d8f7</AUTHKEY>
<ROUTE>4</ROUTE>
<CAMPAIGN>TEST</CAMPAIGN>
<SENDER>OODOOP</SENDER>
<SMS>
<TEXT>HI MANI</TEXT>
<ADDRESS><-TO>8870300358
</-TO>
</ADDRESS>
</SMS>
</MESSAGE>undefined</xml>
I got wrong output, tag mistake.
I know it is an old thread but i hope this can help anyone who seek support.
<?php
//build and array of the data you want to writ as XML
$xml_array = array ("message" => array(
"authkey"=> "68252AGguI2SK45395d8f7",
"route" => 4,
"campaign" => "test",
"sender" => "oooop",
"sms" => array (
"attribute" => "text:Hi Man",
"address" =>array (
"attribute" => "to:8870300358"
)
)
)
);
// create an XML object
$xmlobj = new SimpleXMLElement("<root></root>");
// a convert function
// this will take array in the above format and convert it in to XML Object
function convert($array, $xml){
foreach($array as $key=>$line){
if(!is_array($line)){
$data = $xml->addChild($key, $line);
}else{
$obj = $xml->addChild($key);
if(!empty($line['attribute'])){
$attr = explode(":",$line['attribute']);
$obj->addAttribute($attr[0],$attr[1]);
unset($line['attribute']);
}
convert($line, $obj);
}
}
return $xml;
}
$xmldoc =convert($xml_array,$xmlobj);
// text.xml is a blank file to write the data in it , you should create it first and give it WRITE permission
// in my case i just create it by and
print $xmldoc->asXML('test.xml');
print "<a href='test.xml'> XML file</a>";
:)

Json call in joomla 2.5 component

I'm making a joomla 2.5 component and i trying to set in model or controller (what's the most appropriate ?) a json response of my DB request (for later get the json with angularJS).
Here's my model (with DB response):
<?php
defined('_JEXEC') or die();
jimport( 'joomla.application.component.modelList' );
class MediastoreModelList extends JModelList
{
function getListQuery()
{
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select('id, type, designation', 'marque', 'prix');
$query->from('produits');
return $query;
}
}
My empty controller:
<?PHP
defined('_JEXEC') or die('Restricted access');
jimport('joomla.application.component.controller');
class MediastoreController extends JController
{
}
My view
<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
jimport( 'joomla.application.component.view' );
class MediastoreViewList extends JView
{
function display($tpl = null)
{
$this->items = $this->get('items');
parent::display($tpl);
}
}
and my template
<?php
defined('_JEXEC') or die('Restricted access');
JHTML::script('media/com_mediastore/js/angular.min.js');
JHTML::script('media/com_mediastore/js/app.js');
?>
<?php
echo $this->items;
?>
<div class="content">
<p>Nothing</p>
</div>
How can i do that ?
Thanks a lot,
Antoine
Bit late .....
Hi I am working on something similar.
In your views (sitepart) add an other file called view.raw.php.
You can browse to this file by appending 'format=raw' at the end of the url.
For example: if your component view page in the browser is 'http://test.com/test( IF SEF is on ) then after appending th url shoul be like this
http://test.com/test?format=raw and in case SEF is not on the use & instead of ?
You can use this URL in the angularjs for http.get service.
In view.raw.php file make sure you just echo the results rather than parent::display($tpl);.
This did work for me.
PS: I am using angualrjs too but want to use the component with many menu items and the url keeps changing so am stuck on that part.
Hope this solves your issue.
Regards,
Jai

How can I parse this information with DOM Parser or xpath?

I want to get some data from the URL above, I would like to get all of the torrent names under the search query.
http://kickass.to/usearch/grand%20theft%20auto%20v%20category:ps3/
Currently I got this code, but it just gets the html source from page, it would be great if someone could help me with parsing all the torrent names from the source.
function get_web_page( $url )
{
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_ENCODING => "",
CURLOPT_USERAGENT => "spider",
CURLOPT_AUTOREFERER => true,
CURLOPT_CONNECTTIMEOUT => 120,
CURLOPT_TIMEOUT => 120,
CURLOPT_MAXREDIRS => 10,
);
$ch = curl_init( $url );
curl_setopt_array( $ch, $options );
$content = curl_exec( $ch );
$err = curl_errno( $ch );
$errmsg = curl_error( $ch );
$header = curl_getinfo( $ch );
curl_close( $ch );
$header['errno'] = $err;
$header['errmsg'] = $errmsg;
$header['content'] = $content;
return $header;
}
$data = get_web_page('http://kickass.to/usearch/grand%20theft%20auto%20v%20category:ps3/');
print_r(htmlspecialchars($data['content']));
Is the use of PHP a requirement?
If not, the following groovy script solves your problem:
#Grab('org.codehaus.groovy.modules.http-builder:http-builder:0.6')
import groovyx.net.http.*
import groovy.xml.*
def http = new HTTPBuilder('http://kickass.to/usearch/grand%20theft%20auto%20v%20category:ps3/')
def html = http.get(path: '')
html.'**'.findAll { it.#class == 'torrentname' }.each { torrentNameDiv ->
def titleLink = torrentNameDiv.'*'.findAll { it.#class.text().contains('normalgrey') }?.getAt(0)
def title = titleLink.'*'.findAll { it.name() == 'STRONG' && it.#class == 'red' }.join(' ')
def info = titleLink[0].children().findAll { it instanceof String }.join(' ')
println "title=$title"
println "info=$info"
}
Behind the scenes there are groovy classes like HTTPBuilder, XmlSlurper and GPathResult. The navigation over HTML structure is done via GPathResult.
Documentation here:
http://groovy.codehaus.org/api/groovy/util/slurpersupport/GPathResult.html
http://groovy.codehaus.org/modules/http-builder/home.html
Example here:
http://binarybuffer.com/2012/05/parsing-html-pages-like-a-boss-with-groovy
Unless the html document is xhtml, it is probably not well-formed XML and you'll need an HTML parser rather than an XML parser... or you'll need to preprocess it into xhtml using something like the W3C's "tidy" tool, and then parse it as XML.
Once you get it into a standard W3C DOM, check whether that DOM implementation provides an implementation of XPath. If not, off-the-shelf implementations of XPath that run against user-provided DOMs are also available -- Apache Xalan is one obvious example. Xalan also implements XSLT, so you could combine gathering the data and arranging it into your desired format into a single stylesheet and avoid having to hand-code some of that.