Read returned XML by function with SimpleXML - php

This is sort of confusing to explain, so thank you ahead of time for bearing with me.
I am using Kohana PHP framework to develop an application. I have a model function that accepts parameters for a search, and should return an XML styled page. I need this to be read by the controller with SimpleXML. Any ideas how to do this?
$o = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
$o .= "<feed>\n";
$o .= "\t<search_phrase>$q</search_phrase>\n";
if(isset($entries)){
uasort($entries, 'compare_weight');
/**
* Build the xml data
*/
foreach($modules as $module){
$o .= "\t<search_location>$module</search_location>\n";
}
foreach($entries as $k=>$entry){
$o .= "\n\t<entry>\n";
$o .= "\t\t<title>$entry[title]</title>\n";
$o .= "\t\t<url>$entry[url]</url>\n";
$o .= "\t\t<weight>$entry[weight]</weight>\n";
$o .= "\t\t<module>$entry[module]</module>\n";
if($entry['owners']){
foreach($entry['owners'] as $owner){
$o .= "\t\t<owners>\n";
$o .= "\t\t\t<owner_id>$owner[owner_id]</owner_id>\n";
$o .= "\t\t\t<owner_name>$owner[owner_name]</owner_name>\n";
$o .= "\t\t\t<profile_link>$owner[profile_link]</profile_link>\n";
$o .= "\t\t</owners>\n";
}
}
$o .= "\t</entry>\n";
}
}else{
$o .= "\t<noresult>true</noresult>\n";
}
$o .= "</feed>\n";
return $o;
The controller functions like this... It's the closest I'm able to come to wrapping my head how to do this.
$return= $this->search->search($_GET);
$xml = new SimpleXMLElement($return);
die($xml);
It returns a blank document with 44 blank lines. Any direction would be helpful.

insted of using the constructor of simpleXML try using the simplexml_load_string() function

Try changing the return of your $xml feed to:
return echo $o;

Related

Show to show php object um html modal

I'm trying to show a object in a html modal. Since I don't know the structure beforehand, and the child properties can also be objects or arrays, a simple recursive function seemed to be the way to go, but Im not sure. I have this:
<?php
class LogHelper extends Helper
{
public function warningLogError($body_error)
{
$data = [];
$html = '';
$html .= "<div name='bodyErrosr' class = 'form-group'>";
$html .= "<div class = 'alert alert-warning' role = 'alert'>";
if (!empty($body_error)) {
foreach($body_error as $key => $value) {
$html .= "<li><b>" . $key . "= " . $value. "</b></li>";
}
} else {
$html .= "<li><b>" . 'Error!' . "</b></li>";
}
$html .= "</ul>";
$html .= "</div>";
$html .= "</div>";
return $html;
}
}
But I don't know the structure beforehand, sometimes I receive an object inside object multiple times. How is the best way to do this?
Have a look at: https://packagist.org/packages/symfony/var-dumper
This also handles circular references (where print_r/vardump fail)

Get certain strings only (PHP)

Text:
TestString
HT-Child1 CLASS-Class1
AnotherString
HT-Child2 CLASS-Class2
HT-Child3 CLASS-Class3
HT-Child4 CLASS-Class4
CLASSOFWEEK-Class
What I have so far: (Inside $display->getExtraHTML() is the text). Could someone guide me towards what I need to do to adapt my code to get the results I want.
<?php
$additionalHTML = explode("\n", $display->getExtraHTML());
$html = "";
$html .= "<ul>";
foreach($additionalHTML as $key => $item){
$html .= "<li>$item</li>";
}
$html .= "</ul>";
echo $html;
?>
I know I can use something like this to get string between, but how do I use it to get all the values i need?
$string = strstr($display->getExtraHTML(), "HT-"); // gets all text from HT
$string = strstr($string, "CLASS-", true); // gets all text before CLASS
Can I use both explode and strstr to get to where I want?
Expect HTML markup:
Expected Result: (Get the values from HT- and CLASS-)
<ul>
<li>Child1 Class1</li>
<li>Child2 Class2</li>
<li>Child3 Class3</li>
<li>Child4 Class4</li>
</ul>
Complete solution with preg_match_all function:
$txt = '
TestString
HT-Child1 CLASS-Class1
AnotherString
HT-Child2 CLASS-Class2
HT-Child3 CLASS-Class3
HT-Child4 CLASS-Class4
CLASSOFWEEK-Class';
preg_match_all('/^HT-(\S+)\s+CLASS-(\S+)/m', $txt, $m);
$html = "<ul>";
if (isset($m[1]) && isset($m[2])){
foreach(array_map(null, $m[1], $m[2]) as $pair){
$html .= "<li>". implode(' ', $pair) ."</li>";
}
}
$html .= "</ul>";
echo $html;
The output (push Run code snippet):
<ul><li>Child1 Class1</li><li>Child2 Class2</li><li>Child3 Class3</li><li>Child4 Class4</li></ul>
Here's the solution
<?php
$str = "TestString
HT-Child1 CLASS-Class1
AnotherString
HT-Child2 CLASS-Class2
HT-Child3 CLASS-Class3
HT-Child4 CLASS-Class4
CLASSOFWEEK-Class";
$additionalHTML = explode("\n", $str);
$html = "";
$html .= "<ul>";
foreach($additionalHTML as $key => $item){
if(substr($item,0,3) == "HT-") {
$i = explode(" ",$item);
$a = substr($i[0],3);
$b = substr($i[1],6);
$html .= "<li>$a"." ". "$b</li>";
}
}
$html .= "</ul>";
echo $html;
Result
Child1 Class1
Child2 Class2
Child3 Class3
Child4 Class4
You may use regex, to find the matching lines and extract required data:
if(preg_match("/HT-([A-Za-z0-9]+) CLASS-([A-Za-z0-9]+)/", $item, $output))
{
$html .= "<li>".implode(" ",array_slice($output,1))."</li>";
}

Sort JSON date by date - PHP

I have a site grabbing Confluence blogpost data. The API im using doesn't appear to have a sort feature. Can anyone help me get PHP sorting the posts on the page by the JSON date, i need the most recent first. Thanks!
<?php
require_once($_SERVER["DOCUMENT_ROOT"].'/layout/layout.inc.php');
require_once($_SERVER["DOCUMENT_ROOT"].'/functions/general.inc.php');
$layout = new my_layout();
$layout->title('IT KB Search');
$layout->content("<div class='border'>");
$layout->content('<h1>IT Support Knowledge Base - Search Results</h1>');
$baseUrl = 'https://website.atlassian.net/wiki';
$url = $baseUrl.'/rest/api/content?spaceKey=KB&type=blogpost&start=0&limit=10&expand=space,history,body.view,metadata.labels';
// To enable authenticated search:
// $url .= "&os_username=$username&os_password=$password";
$response = file_get_contents($url);
$response = json_decode($response);
$results = $response->results;
$html .= '<dl style=list-style: none;>';
foreach($results as $item) {
$date = $item-> history-> createdDate;
$html .= '<strong><a href="';
$html .= $baseUrl. $item-> _links-> webui;
$html .= '" target="_blank">';
$html .= $item->title;
$html .= ' - ';
$html .= date("d/m/Y",strtotime($date));
$html .= '</a></strong><br>';
$html .= $item->body-> view-> value;
$html .= '<br>';
}
$html .= '</dl>';
$layout->content($html);
$layout->content('</div>');
$layout->render();
Before foreach loop, you can use usort like this
usort($results, function ($a, $b) {
return strtotime($a->history->createdDate) - strtotime($b->history-> createdDate);
});
Once done, $result will have data in sorted order $a-$b will give you data in ascending order and $b-$a will give you data in descending order
You can try something like :-
function date_compare($a, $b)
{
$t1 = strtotime($a['datetime']);
$t2 = strtotime($b['datetime']);
return $t1 - $t2;
}
usort($results, 'date_compare');
You can declare the function date_compare in your php file and use the statement:-
usort($results, 'date_compare');
just before the for each loop

Dynamic html returns nothing

I'm in the process of learning php so forgive me if this is a silly question. I'm trying to make a dynamic gallery that looks through a folder(./JIN/snoii/) and produces the html code for the number of items in said folder. This code I've written isnt returning anything when the file has images(currently has over a hundred) can some one tell me where I messed up or point me in the right direction. Thanks in advance
$CurrentViewFile = "snoii";
function showGallery(){
global $CurrentViewFile;
$galleryHTML = "<h1>Dynamic gallery</h1>";
$galleryHTML .= "<ul>";
$folderToview = "JIN/";
$folderToview .= $CurrentViewFile;
$images = new DirectoryIterator($folderToview);
while($images->valid()){
$galleryHTML .= "<li>!!</li>";
$images->next();
}
$galleryHTML .= "</ul>";
return $galleryHTML;
}
return showGallery();
Your DirectoryIterator makes the problem,
Please try like this
$CurrentViewFile = "/snoii";
function showGallery(){
global $CurrentViewFile;
$galleryHTML = "<h1>Dynamic gallery</h1>";
$galleryHTML .= "<ul>";
$folderToview = "JIN/";
$CurrentViewFile .= $folderToview;
foreach (new DirectoryIterator($CurrentViewFile) as $images) {
if($images->valid())
$galleryHTML .= "<li>!!</li>";
$images->next();
}
$galleryHTML .= "</ul>";
return $galleryHTML;
}
$output_data = showGallery();
echo $output_data;
If you want to get file name from the iterator you should use like this,
$images->getFilename()

creating own classes in CI

I am trying to make a own class in CodeIgniter and therefore I have made a file in the folder
libraries
This class is called
Menu
And it contains a class to create a navigation bar for my website. this class is like
class Menu {
public function draw($menu) {
$CI =& get_instance();
$output = '';
foreach ($menu as $key => $value) {
$output .= "<li>";
if (is_array($value)) {
if (strpos($key, '|') !== false) {
$param = explode('|', $key);
$output .= anchor($param[1], $param[0]);
} else {
$output .= anchor('#', $key);
}
$output .= PHP_EOL."<ul>".PHP_EOL;
$output .= draw($value);
$output .= "</ul>".PHP_EOL."</li>".PHP_EOL;
} else {
$output .= anchor($key, $value, $CI->uri->slash_segment(1, 'leading') == $key ? 'class="active"' : '');
$output .= "</li>".PHP_EOL;
}
}
return $output;
}
}
I have put this class in my config file as autoload under libraries
$autoload['libraries'] = array('menu');
When I call the class to use it I do this
<?php
$m = new Menu();
echo $m->draw($menu);
?>
But unfortunately I get this error
Fatal error: Call to undefined function draw() in /Users/username/Sites/infinity2.0/application/libraries/Menu.php on line 22
Line 22 is $output .= draw($value);
But I don't know how to solve this I think its because of calling its own method again.. any help is welcome and appreciated. :)
Change
$output .= draw($value);
to
$output .= $this->draw($value);
$this refers to the current object, so if you want to recursively call draw() within itself, you need to use it to refer to it..
You might want to read the explanation from the php.net website: http://php.net/manual/en/language.oop5.basic.php

Categories