How to echo XML as simple string? - php

I am not able to understand the behaviour of the code :
Input :
<?php
function polldaddy_choices($choices) {
foreach ($choices as $choice) {
$answer = "<pd:answer>
<pd:text>" . $choice . "</pd:text>
</pd:answer>";
echo $answer;
}
}
$total_choices = array('yes' , 'no' , 'do not know');
$ans = polldaddy_choices($total_choices);
$xml = "world" . $ans . "hello" ;
echo $xml;
?>
Output :
<pd:answer>
<pd:text></pd:text>
</pd:answer><pd:answer>
<pd:text></pd:text>
</pd:answer><pd:answer>
<pd:text></pd:text>
</pd:answer>worldhello
Why the string are coming at the end of the output ?
Here is the link on codepad : http://codepad.org/2dbiCelb

Your function was echoing the xml code straight away. In the code below you will see I create a variable ($answer = "";) and then append the xml at the end of the variable by using ".=". At the end of the function I return the value of $answer.
When you call the function then ($ans = polldaddy_choices($total_choices);), it will place the return value of the function into your $ans variable.
<?php
function polldaddy_choices($choices) {
$answer = "";
foreach ($choices as $choice) {
$answer.= "<pd:answer>
<pd:text>" . $choice . "</pd:text>
</pd:answer>";
}
return $answer;
}
$total_choices = array('yes' , 'no' , 'do not know');
$ans = polldaddy_choices($total_choices);
$xml = "world" . $ans . "hello" ;
echo $xml;
?>

Your function is not retuning anything. You are echoing directly in that function.
So first you call polldaddy_choices, which echos the html. Then, you echo:
$xml = "world" . "" . "hello" ;

Because you are echoing the output in your polldaddy_choices function. So the following:
$ans = polldaddy_choices($total_choices); Is actually printing the XML, and:
$xml = "world" . $ans . "hello"; will simply be printing worldhello, as $ans === null
I think you probably want to be doing something more like:
function polldaddy_choices($choices) {
$answers = array();
foreach ($choices as $choice) {
$answer = "<pd:answer>
<pd:text>" . $choice . "</pd:text>
</pd:answer>";
$answers[] = $answer;
}
return implode("\n", $answers);
}

Related

Get link by id API/URL

I have this code
<?php
// The result of the request:
$content = <<<END_OF_STRING
[{"id":"2972","name":"MBC 1","link":"http://46.105.112.116/?watch=TR/mbc1-ar&token=RED_cexVeBNZ8mioQnjmGiYNEg==,1643770076.5266113827&t=1&s=2&p=1&c=BR&r=1351&lb=1","epg":"https://epg.cdnrdn.com/MBC1En.ae-20220201.xml","dvr":"disabled","language":"Arabic","category":"TOP 100","logo":"http://files.rednetcontent.com/chlogo/mbc1.png"},{"id":"1858","name":"MBC 2","link":"http://46.105.112.116/?watch=TN/mbc2-ar&token=RED_cexVeBNZ8mioQnjmGiYNEg==,1643770076.5266113827&t=1&s=2&p=1&c=BR&r=1351&lb=1","epg":"https://epg.cdnrdn.com/MBC2En.ae-20220201.xml","dvr":"disabled","language":"Arabic","category":"TOP 100","logo":"http://files.rednetcontent.com/chlogo/mbc2.png"},{"id":"1859","name":"MBC 3","link":"http://46.105.112.116/?watch=TN/mbc3-ar&token=RED_cexVeBNZ8mioQnjmGiYNEg==,1643770076.5266113827&t=1&s=2&p=1&c=BR&r=1351&lb=1","epg":"https://epg.cdnrdn.com/-20220201.xml","dvr":"disabled","language":"Arabic","category":"TOP 100","logo":"http://files.rednetcontent.com/chlogo/mbc3.png"}]
END_OF_STRING;
$items = json_decode($content);
// To access the first one:
echo "\nFirst link = " . $items[0]->link . "\n";
I want to get link by id.
Can anyone help?
More ore less what you need could be:
<?php
// The result of the request:
$content = <<<END_OF_STRING
[{"id":"2972","name":"MBC 1","link":"http://46.105.112.116/?watch=TR/mbc1-ar&token=RED_cexVeBNZ8mioQnjmGiYNEg==,1643770076.5266113827&t=1&s=2&p=1&c=BR&r=1351&lb=1","epg":"https://epg.cdnrdn.com/MBC1En.ae-20220201.xml","dvr":"disabled","language":"Arabic","category":"TOP 100","logo":"http://files.rednetcontent.com/chlogo/mbc1.png"},{"id":"1858","name":"MBC 2","link":"http://46.105.112.116/?watch=TN/mbc2-ar&token=RED_cexVeBNZ8mioQnjmGiYNEg==,1643770076.5266113827&t=1&s=2&p=1&c=BR&r=1351&lb=1","epg":"https://epg.cdnrdn.com/MBC2En.ae-20220201.xml","dvr":"disabled","language":"Arabic","category":"TOP 100","logo":"http://files.rednetcontent.com/chlogo/mbc2.png"},{"id":"1859","name":"MBC 3","link":"http://46.105.112.116/?watch=TN/mbc3-ar&token=RED_cexVeBNZ8mioQnjmGiYNEg==,1643770076.5266113827&t=1&s=2&p=1&c=BR&r=1351&lb=1","epg":"https://epg.cdnrdn.com/-20220201.xml","dvr":"disabled","language":"Arabic","category":"TOP 100","logo":"http://files.rednetcontent.com/chlogo/mbc3.png"}]
END_OF_STRING;
$items = json_decode($content);
$id = 1859;
$desiredLink = '';
foreach ($items as $item) {
if ($id == $item->id) {
$desiredLink = $item->link;
}
}
// To access the first one:
echo "\nDesired link = " . $desiredLink . "\n";
This will output: Desired link = http://46.105.112.116/?watch=TN/mbc3-ar&token=RED_cexVeBNZ8mioQnjmGiYNEg==,1643770076.5266113827&t=1&s=2&p=1&c=BR&r=1351&lb=1
If you prefer, ... I've also implemented a little class to do the same job:
class Finder {
public function __construct(private string $content) {}
public function getLinkById(int $id) {
$items = json_decode($this->content);
foreach ($items as $item) {
if ($id == $item->id) {
return $item->link;
}
}
}
}
// To access the first one:
echo "\nDesired link = " . (new Finder($content))->getLinkById($id) . "\n";

How can I check If I get empty file_get_html in PHP HTML Dom?

I am getting JSON data through visiting a link using PHP HTML DOM, but sometimes, I get an empty page so I want to know that how can I really check if page is empty so that I can skip it by using continue in for loop
I am checking it through :
if (empty($jsondata))
But I always get TRUE never gets false even if page is returned empty
Here is my code :
<?php
$prefix = $_POST['prefix'];
$start_product = $_POST['start_product'];
$end_product = $_POST['end_product'];
set_time_limit(0);
for ($i=$start_product; $i <= $end_product; $i++) {
include('simple_html_dom.php');
$prefix ="00";
$i= "11";
$jsondata = file_get_html('http://www.ewallpk.com/index.php?controller=search&q=A'.$prefix.$i.'&limit=10&timestamp=1445547668758&ajaxSearch=1&id_lang=1');
if (!empty($jsondata)) {
$data = json_decode($jsondata, true);
$product = file_get_html($data[0]["product_link"]);
$product_name= "";
foreach($product->find('div[id=pb-left-column] h1') as $element) {
$product_name.=$element->innertext . '<br>';
}
$product_name = explode("_", $product_name);
$count = count($product_name);
if ($count < 3) {
$product_name=$product_name[0];
} else {
$product_name = "Error";
}
$product_description= "";
foreach($product->find('div[id=short_description_content]') as $element) {
$product_description.=$element->plaintext . '<br>';
}
$product_price= "";
foreach($product->find('p[class=our_price_display] span') as $element) {
$product_price.=$element->innertext . '<br>';
}
$image_link= "";
foreach($product->find('img[id=bigpic]') as $element) {
$image_link.=$element->src;
}
$content = file_get_contents($image_link);
file_put_contents('item_images/A'.$prefix.$i.'.jpg', $content);
echo "<strong>Product No : </strong> A".$prefix.$i."</br>";
echo "<strong>Product Name : </strong>".$product_name."</br>";
echo "<strong>Product Description : </strong>".$product_description;
echo "<strong>Product Price : </strong>".$product_price."</br></br></br>";
} else {
continue;
}
}
?>
You're probably getting some whitespace in the empty response, so trim it off before testing. You also should be using file_get_contents, since the response is not HTML.
$jsondata = file_get_contents('http://www.ewallpk.com/index.php?controller=search&q=A'.$prefix.$i.'&limit=10&timestamp=1445547668758&ajaxSearch=1&id_lang=1');
$jsondata = trim($jsondata);
if (!empty($jsondata)) {
...
}

PHP Foreach inside variable with equals

I have a variable that equals some simple data as shown below
$var = 'hello names here how are yous?';
what i wish to achieve is have a foreach loop inside the $var but i have tried various ways with just no luck, always throwing errors.
Below is somewhat what i what to do.
$var = 'hello '.foreach($datas as $data) { echo $data }.' how are yous?';
echo $var;
which would output - hello Mike Daniel Steve how are yous?
any help appreciated.
======EDIT========
im trying to write to file the looped contents with below code.
$datas = 'Name, Name2, Name4';
$var = ''.foreach($datas as $data) { echo $data }.'
$default_file = 'media/default.php';
$default_file_handle = fopen($default_file, 'w') or die('Cannot open file: '.$default_file);
$default_data = '
'.$var.'//each value to be a new line
Name2 //example
Name4 //example
etc
';
fwrite($default_file_handle, $default_data);
so basically im write to file each value in the loop to a new line. I can write just normal content but getting a loop in their im struggling with
$var = 'hello';
foreach($datas as $data) {
$var .= ' '.$data.' ';
}
$var .= ' how are you?';
echo $var;
that should do it
$arr = array("Mike", "John");
echo "Hello " . implode(" ", $arr) . ", how are you?";
implode is your friend. Implode joins array elements together into one single string. The separator between each array element is the first parameter - in this case a blank.
You can use implode:
$var = 'hello '.implode(' ', $datas) .' how are yous?';
echo $var;
To achieve this you either have to insert the foreach loop like this:
echo "hello ";
foreach($datas as $data) {
echo $data;
}
echo " how are you?";
or you can use an extra variable and the implode method:
$dataString = implode(" ", $datas);
echo "hello " . $dataString . " how are you?";
You can do this following way.
<?php
$data = array('Mike Daniel','john doe');
foreach ($data as $value) {
$result = 'hello '. $value. ' how are you?'. '</br>';
echo $result;
}

Getting a random object from an array in PHP

First and foremost, forgive me if my language is off - I'm still learning how to both speak and write in programming languages. How I can retrieve an entire object from an array in PHP when that array has several key, value pairs?
<?php
$quotes = array();
$quotes[0] = array(
"quote" => "This is a great quote",
"attribution" => "Benjamin Franklin"
);
$quotes[1] = array(
"quote" => "This here is a really good quote",
"attribution" => "Theodore Roosevelt"
);
function get_random_quote($quote_id, $quote) {
$output = "";
$output = '<h1>' . $quote["quote"] . '.</h1>';
$output .= '<p>' . $quote["attribution"] . '</p>';
return $output;
} ?>
<?php
foreach($quotes as $quote_id => $quote) {
echo get_random_quote($quote_id, $quote);
} ?>
Using array_rand and var_dump I'm able to view the item in the browser in raw form, but I'm unable to actually figure out how to get each element to display in HTML.
$quote = $quotes;
$random_quote = array_rand($quote);
var_dump($quote[$random_quote]);
Thanks in advance for any help!
No need for that hefty function
$random=$quotes[array_rand($quotes)];
echo $random["quote"];
echo $random["attribution"];
Also, this is useless
<?php
foreach($quotes as $quote_id => $quote) {
echo get_random_quote($quote_id, $quote);
} ?>
If you have to run a loop over all the elements then why randomize hem in the first place? This is circular. You should just run the loop as many number of times as the quotes you need in output. If you however just need all the quotes but in a random order then that can simply be done in one line.
shuffle($quotes); // this will randomize your quotes order for loop
foreach($quotes as $qoute)
{
echo $quote["quote"];
echo $quote["attribution"];
}
This will also make sure that your quotes are not repeated, whereas your own solution and the other suggestions will still repeat your quotes randomly for any reasonably sized array of quotes.
A simpler version of your function would be
function get_random_quote(&$quotes)
{
$quote=$quotes[array_rand($quotes)];
return <<<HTML
<h1>{$quote["quote"]}</h1>
<p>{$quote["attribution"]}</p>
HTML;
}
function should be like this
function get_random_quote($quote_id, $quote) {
$m = 0;
$n = sizeof($quote)-1;
$i= rand($m, $n);
$output = "";
$output = '<h1>' . $quote[$i]["quote"] . '.</h1>';
$output .= '<p>' . $quote[$i]["attribution"] . '</p>';
return $output;
}
However you are not using your first parameter-$quote_id in the function. you can remove it. and call function with single parameter that is array $quote
Why don't you try this:
$quote = $quotes;
$random_quote = array_rand($quote);
$random = $quote[$random_quote];
echo '<h1>' . $random["quote"] . '.</h1><br>';
echo '<p>' . $random["attribution"] . '</p>';
Want to create a function:
echo get_random_quote($quotes);
function get_random_quote($quotes) {
$quote = $quotes;
$random_quote = array_rand($quote);
$random = $quote[$random_quote];
return '<h1>' . $random["quote"] . '.</h1><br>'.'<p>' . $random["attribution"] . '</p>';
}
First, you dont need the $quote_id in get_random_quote(), should be like this:
function get_random_quote($quote) {
$output = "";
$output = '<h1>' . $quote["quote"] . '.</h1>';
$output .= '<p>' . $quote["attribution"] . '</p>';
return $output;
}
And I cant see anything random that the function is doing. You are just iterating through the array:
foreach($quotes as $quote_id => $quote) {
echo get_random_quote( $quote);
}
According to http://php.net/manual/en/function.array-rand.php:
array_rand() Picks one or more random entries out of an array, and
returns the key (or keys) of the random entries.
So I guess $quote[$random_quote] should return your element, you can use it like:
$random_quote = array_rand($quotes);
echo get_random_quote($quote[$random_quote]);

Sorting strings, in a function, is my logic faulty or?

i need to sort some strings and match them with links, this is what i do:
$name_link = $dom->find('div[class=link] strong');
Returns array [0]-[5] containing strings such as NowDownload.eu
$code_link = $dom->find('div[class=link] code');
Returns links that match the names from 0-5, as in link [0] belongs to name [0]
I do not know the order in which they are returned, NowDownload.Eu, could be $code_link[4] or $code_link [3], but the name array will match it in order.
Now, i need $code_link[4] // lets say its NowDownload.Eu to become $link1 every time
so i do this
$i = 0;
while (!empty($code_link[$i]))
SortLinks($name_link, $code_link, $i); // pass all links and names to function, and counter
$i++;
}
function SortLinks($name_link, $code_link, &$i) { // counter is passed by reference since it has to increase after the function
$string = $name_link[$i]->plaintext; // name_link is saved as string
$string = serialize($string); // They are returned in a odd format, not searcheble unless i serialize
if (strpos($string, 'NowDownload.eu')) { // if string contains NowDownload.eu
$link1 = $code_link[$i]->plaintext;
$link1 = html_entity_decode($link1);
return $link1; // return link1
}
elseif (strpos($string, 'Fileswap')) {
$link2 = $code_link[$i]->plaintext;
$link2 = html_entity_decode($link2);
return $link2;
}
elseif (strpos($string, 'Mirrorcreator')) {
$link3 = $code_link[$i]->plaintext;
$link3 = html_entity_decode($link3);
return $link3;
}
elseif (strpos($string, 'Uploaded')) {
$link4 = $code_link[$i]->plaintext;
$link4 = html_entity_decode($link4);
return $link4;
}
elseif (strpos($string, 'Ziddu')) {
$link5 = $code_link[$i]->plaintext;
$link5 = html_entity_decode($link5);
return $link5;
}
elseif (strpos($string, 'ZippyShare')) {
$link6 = $code_link[$i]->plaintext;
$link6 = html_entity_decode($link6);
return $link6;
}
}
echo $link1 . '<br>';
echo $link2 . '<br>';
echo $link3 . '<br>';
echo $link4 . '<br>';
echo $link5 . '<br>';
echo $link6 . '<br>';
die();
I know they it finds the link, i have tested it before, but i wanted to make it a function, and it messed up, is my logic faulty or is there an issue with the way i pass the variables/ararys ?
I don't know why you pass $i as reference since you use it just for reading it. You could return an array contaning the named links and using it like so :
$all_links = SortLinks($name_link,$code_link);
echo $all_links['link1'].'<br/>';
echo $all_links['link2'].'<br/>';
You will have to put your loop inside the function, not outside.

Categories