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";
Related
I've created a page that grabs data from a CSV (http://liamjken.com/aim-parse/aim-websites-new.csv) and displays it on this page http://www.liamjken.com/aim-parse/parse.php?17
?17 references the row in the csv file. so if I change that to ?10 it pulls the info from a different row.
What I would like to do instead of using the row number is use the $vin_num value. so if I put ?1FMCU9GD9KUC40413 at the end of the URL it would display the row that contains that Number.
here is the code I have currently, its basically cobbled together from multiple different trends I found so if you notice other potential problems id be happy to hear about them.
<?php
$qstring = $_SERVER['QUERY_STRING'];
$row = $qstring; // The row that will be returned.
$data = get_row('aim-websites-new.csv', $row);
'<pre>'.print_r($data).'</pre>';
function get_row($csv, $row) {
$handle = fopen("$csv", 'r');
$counter = 0;
$result = '';
while ( ($data = fgetcsv($handle)) !== FALSE ) {
$counter++;
if ( $row == $counter ) {
$vin_num="$data[12]";
$model="$data[10]";
$make="$data[9]";
$year="$data[8]";
ob_start();
?>
<h1>VIN: <?php echo $vin_num; ?></h1>
<h1>Year: <?php echo $year; ?></h1>
<h1>Make: <?php echo $make; ?></h1>
<h1>Model: <?php echo $model; ?></h1>
<?php
$output = ob_get_clean();
ob_flush();
return $output;
}
}
}
?>
<?php
function extract_data($file)
{
$raw = file($file); // file() puts each line of file as string in array
$keys = str_getcsv(array_shift($raw)); // extract the first line and convert into an array
// Look through the rest of the lines and combine them with the header
$data = [];
foreach ($raw as $line) {
$row = str_getcsv($line);
$data[] = array_combine($keys, $row);
}
return $data;
}
function get_record($data, $vin)
{
foreach ($data as $record) {
if ($record['VIN'] === $vin)
return $record;
}
return null;
}
$data = extract_data('aim-websites-new.csv');
$vin = $_SERVER['QUERY_STRING'];
if (empty($vin)) {
echo '<h1>No VIN provided</h1>';
exit;
}
$record = get_record($data, $vin);
if ($record === null) {
echo '<h1>No record found</h1>';
exit;
}
echo '<h1>' . $record['VIN'] . '</h1>';
echo '<h1>' . $record['Year'] . '</h1>';
echo '<h1>' . $record['Make'] . '</h1>';
echo '<h1>' . $record['Model'] . '</h1>';
echo '<pre>' . print_r($record, true) . '</pre>';
If you don't trust that the records will have valid VINs, you can use the code posted here to validate: How to validate a VIN number?
I have a Laravel app, which the following PHP code:
public function handle()
{
$post_item->category_id = $source->category_id;
$post_item->featured = 0;
$post_item->type = Posts::TYPE_SOURCE;
$post_item->render_type = $item['render_type'];
$post_item->source_id = $source->id;
$post_item->description = is_array($item['description'])?'':$item['description'];
$post_item->featured_image = $item['featured_image'];
$post_item->video_embed_code = $item['video_embed_code'];
$post_item->dont_show_author_publisher = $source->dont_show_author_publisher;
$post_item->show_post_source = $source->show_post_source;
$post_item->show_author_box = $source->dont_show_author_publisher == 1 ? 0 : 1;
$post_item->show_author_socials = $source->dont_show_author_publisher == 1 ? 0 : 1;
$post_item->rating_box = 0;
$post_item->created_at = $item['pubDate'];
$post_item->views = 1;
$post_item->save();
$this->createTags($item['categories'], $post_item->id);
// This is where I want to add my echo
}
public function createTags($tags, $post_id)
{
$post_tags = PostTags::where('post_id', $post_id)->get();
foreach ($post_tags as $post_tag) {
Tags::where('id', $post_tag->tag_id)->delete();
}
PostTags::where('post_id', $post_id)->delete();
foreach ($tags as $tag) {
$old_tag=Tags::where('title',$tag)->first();
if(isset($old_tag))
{
$pt = new PostTags();
$pt->post_id = $post_id;
$pt->tag_id = $old_tag->id;
$pt->save();
}
else {
$new_tag = new Tags();
$new_tag->title = $tag;
$new_tag->slug = Str::slug($tag);
$new_tag->save();
$pt = new PostTags();
$pt->post_id = $post_id;
$pt->tag_id = $new_tag->id;
$pt->save();
}
}
}
Im trying to echo the the title along with the tags, right after the commented place, but it fails to provide the correct output. I was wondering if Im using the correct way or my workaround is completely wrong.
Im using this code in the commented part:
$tweet = $post_item->title . ' tags: ' . $post_item->tags;
After doing some tests, I realized that if I use
var_dump($tag);
right after
foreach ($tags as $tag)
at my createTags function, it seems that all tags are output correctly.
Im wondering if I can store all $tags inside the createTag function's foreach, under a globally accessed variable that would be used in the initial handle function echoed.
Guessing the post item model has a relation "tags" you could try this:
$tweet = $post_item->title . ' tags: ' . implode(', ', $post_item->tags->toArray());
Also if you would just like to echo the tags on the commented place, try this:
echo implode(',', $item['categories']);
try if $post_item->tags - is array then
$tweet = $post_item->title . ' tags: ' . implode(', ', $post_item->tags);
if - collection then
$tweet = $post_item->title . ' tags: ' . $post_item->tags->join(', ');
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×tamp=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×tamp=1445547668758&ajaxSearch=1&id_lang=1');
$jsondata = trim($jsondata);
if (!empty($jsondata)) {
...
}
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);
}
I only want the first and the second last Area nodes - how would I do that here?
$url = "http://developer.multimap.com/API/geocode/1.2/OA10081917657704697?qs=Byker&countryCode=GB";
$results = simplexml_load_file($url);
foreach($results->Location as $location) {
echo "<hr />";
foreach($location->Address as $address) {
foreach($address->Areas as $areas) {
foreach($areas->Area as $area) {
echo $area;
echo "<br />";
}
}
}
}
Update: If you have those foreach-loops anyway you can simply use:
$url = "http://developer.multimap.com/API/geocode/1.2/OA10081917657704697?qs=Byker&countryCode=GB";
$results = simplexml_load_file($url);
foreach($results->Location as $location) {
foreach($location->Address as $address) {
foreach( $address->Areas as $areas) {
// <-- todo: add test if those two elements exist -->
echo $areas->Area[0], ' - ', $areas->Area[count($areas->Area)-1], "\n";
}
}
}
You can use XPath for this.
<?php
$doc = new SimpleXMLElement('<foo>
<bar>a</bar>
<bar>b</bar>
<bar>c</bar>
<bar>x</bar>
<bar>y</bar>
<bar>z</bar>
</foo>');
$nodes = $doc->xpath('bar[position()=1 or position()=last()-1]');
foreach( $nodes as $n ) {
echo $n, "\n";
}
prints
a
y
see also:
PHP Manual: SimpleXMLElement::xpath()
XPath: predicates
XPath: position()
XPath: last()
Here it is:
<?php
$url = 'http://developer.multimap.com/API/geocode/1.2/OA10081917657704697?qs=Byker&countryCode=GB';
$results = simplexml_load_file($url);
$areas = array();
foreach ($results->Location->Address->Areas->Area as $area)
{
$areas[] = (string) $area;
}
$first = $areas[0];
$second_last = $areas[count($areas)-2];
?>