Get data from XML in PHP with a variable - php

I started mixing XML with PHP today and I'm pretty bad at it, even though it looks super simple.
Right now, I'm trying to make something that sounds very easy but I can't understand how it works. I'm basically trying to create a fake mailbox for a game.
So I stored my emails in an XML file, classed by categories (received, sent, etc.). I managed to get the list of emails depending on the category, but I can't get to the part where I click on an email and it shows the content of this particular email.
Here is my simplified code:
XML :
<mailbox>
<received>
<expediter>James</expediter>
<content>Blah blah blah</content>
</received>
<received>
<expediter>Paul</expediter>
<content>Bluh bluh bluh</content>
</received>
<sent>
<expediter>Jack</expediter>
<content>Blah blah blah</content>
</sent>
<sent>
<expediter>John</expediter>
<content>Bluh bluh bluh</content>
</sent>
</mailbox>
XML;
?>
PHP :
<?php
include 'emails.php';
$emails = new SimpleXMLElement($xmlstr);
$cat = $_GET['cat'];
if(!isset($_GET['id'])){
$i = 0;
foreach($emails->$cat as $mailbox){
echo ''.$mailbox->expediter.'<br />';
$i++;
}
}
else{
$id = $_GET['id'];
echo $emails->$cat[$id]->content;
}
?>
So if there is no ID in the url, it shows the list of expediters with links to the email and if there is an ID in the url, it should show the content of the email designed by this number.
It works if I write manually :
echo $emails->received[1]->content;
But of course, I want that part to be dynamic and it doesn't work with :
echo $emails->$cat[$id]->content;
Is there any way to do that?
Thank you!
Camille

Try this:
$a = new stdClass();
$b = new stdClass();
$b->field = 5;
$a->list = array(
1 => $b
);
print_r($a);
$param = 'list';
$id = 1;
print_r($a->list[1]->field); // outputs 5;
print_r($a->{$param}[$id]->field); // outputs 5;
The key is:
$a->{$param}[$id]->field // notice the curly brackets.
Adapting to your question, you should use:
echo $emails->{$cat}[$id]->contenu;
As a good practice, you might want to check if it exists first:
if(isset($emails->{$cat}[$id])){
// echo it here, after you know it exists
}
You can see it online at 3v4l example

Related

How to output a code stored in variable to code?

I am new to this but making some real good progres :-).
It is all in PHP, JSON.
I am stuck at this simple question and cannot find an answer anywhere on the web.
Here is my problem:
I have code stored inside the variable.
I want to output that code just below some other code and I want it to be interpreted.
Alternatively I want the code from the $variable to be runned in the middle of my code.
I have tried echo, print, var_dump etc. their output is human readable and I want it to be just runned in the middle of my code.
$variable='
$request[method1][0] = array();
$request[method1][0][var1] = 1;
$request[method1][0][var2] = 13;
$request[method1][0][var3] = nonrefundable;
$request[method1][0][var4] = 1;
$request[method1][0][var5] = 96;
$request[method1][0][var6] = "2019-02-12";
$request[method1][0][var7] = whole;'
needless to say it is exactly 6211 times longer
$request = array();
$request['authenticate'] = array();
$request['authenticate']['systemKey'] =
$request['authenticate']['systemLogin'] =
$request['authenticate']['lang'] = 'eng';
output ($variable)
I am looking for that 'output' function or some other method. Later on $request is encoded with 'json_encode'
I expect it to run as the code from the variable would be just pasted below.
To display a variable in PHP, you have several options, each being more useful in certain contexts:
echo (https://php.net/echo)
var_dump (https://php.net/var_dump)
print_r (https://php.net/print_r):
They are used the following way:
echo $variable;
var_dump($variable);
print_r($variable);
If you wish to recover your result from a JavaScript script for example, you would encode it as JSON and then echo it:
echo json_encode($variable);

How can I sanitise the explode() function to extract only the marker I require?

I have some php code that extracts a web address. The object I have extracted is of the form:
WEBSITE?flage=2&fgast=48&frat=1&sort=D&fsrc=2&wid=bf&page=1&id=16123012&source=searchresults
Now in PHP I have called this object $linkHREF
I want to extract the id element only and put it into an array (I'm bootstrapping this process to get multiple id's)
So the command is:
$detailPagePathArray = explode("id=",$linkHREF); #Array
Now the problem is the output of this includes what comes after the id tag, so the output looks like:
echo $detailPagePathArray[0] = WEBSITE?flage=2&fgast=48&frat=1&sort=D&fsrc=2&w
echo $detailPagePathArray[1] = bf&page=1&
echo $detailPagePathArray[2] = 16123012&source=searchresults
Now the problem is obvious, where it'd firstly picking up the "id" in the "wid" marker and cutting it there, however the secondary problem is it's also picking up all the material after the actual "id". I'm just interested in picking up "16123012".
Can you please explain how I can modify my explode command to point it to the particular marker I'm interested in?
Thanks.
Use the built-in functions provided for the purpose.
For example:
<?php
$url = 'http://www.example.com?flage=2&fgast=48&frat=1&sort=D&fsrc=2&wid=bf&page=1&id=16123012&source=searchresults';
$qs = parse_url($url);
parse_str($qs['query'], $vars);
$id = $vars['id'];
echo $id; // 16123012
?>
References:
parse_url()
parse_str()
if you are sure that you are getting &id=123456 only once in your object, then below
$linkHREF = "WEBSITE?flage=2&fgast=48&frat=1&sort=D&fsrc=2&wid=bf&page=1&id=16123012&source=searchresults";
$str = current(explode('&',end(explode('&id', $linkHREF,2))));
echo "id" .$str; //output id = 16123012

Infinite Loop Banner

Excuse me. I am beginner for this code web :)
I have 3 images for my banner...
I dont want appear image banner same as random() statement
I have tried an array multidimensional php
$images[0] = ("1.jpg","2.jpg","3.jpg");
$images[1] = ("2.jpg","3.jpg","1.jpg");
$images[2] = ("3.jpg","1.jpg","2.jpg");
I want to change the position every refresh of my image like $images(array) above
My code like this :
<?php
$a=1;
$i=3;
while($a<=$i){
$images[$a] = ("$appear");}
//$appear is list of image above but I create it with random()
?>
I have 2 question for this problem :
I want to get value where $a=1 and $a=2 images appear as $images[1] = ("2.jpg","3.jpg","1.jpg");and$images[2] = ("3.jpg","1.jpg","2.jpg");
Could I get that value? which code would I use?
I want to use javascript for recall $a=1; if $a had finished (for loop again)....
Could you help me?
I am sorry if My Attitude and My Language is fall apart
I hope you can understand My Idea
Thank you for you greatful ^^
Are you thinking about this.....
for refreshing you have to use session variables
<?php
session_start();
if(!isset($_session['a']))
$_session['a'] = 1;
$a = $_session['a']; // retrieves the value even you refreshes the page
$i=3;
while(1){
$images[$a] = ("$appear");
$a = $a + 1;
if($a>3)
$a=1;
$_session['a'] = $a; //stores the value even you refreshes the page
}
?>
it will reset the $a value to 1 when it reaches 3
If is this you are looking for..?
I think you just have some syntax issues.
Arrays in PHP are in this form:
$images = array('1.jpg', '2.jpg', '3.jpg');
if you want a random image use:
$image = array_rand($images);
Cheers!

Using Simple HTML DOM to extract an 'a' URL

I have this code for scraping team names from a table
$url = 'http://fantasy.premierleague.com/my-leagues/303/standings/';
$html = #file_get_html($url);
//Cut out the table
$FullTable = $html->find('table[class=ismStandingsTable]',0);
//get the text from the 3rd cell in the row
$teamname = $FullTable->find('td',2)->innertext;
echo $teamname;
This much works.. and gives this output....
Why Always Me?
But when I add these lines..
$teamdetails = $teamname->find('a')->href;
echo $teamdetails;
I get completely blank output.
Any idea why? I am trying to get the /entry/110291/event-history/33/ as one variable, and the Why Always Me? as another.
Instead do this:
$tdhtml = DOMDocument::loadHTML($teamdetails);
$link = $tdhtml->getElementsByTagName('a');
$url = $link->item(0)->attributes->getNamedItem('href')->nodeValue;
$teamdetails = $teamname->find('a')->href;
^^^^^^^^^---- never defined in your code
I also fail to see how your "works" code could possibly work. You don't define $teamname in there either, so all you'd never get is the output of a null/undefined variable, which is...no output all.
Marc B is right, I get that you don't have to initialize a variable, but he is saying you are trying to access a property of said variable:
$teamdetails = $teamname->find('a')->href;
^^^^^^^^^---- never defined in your code
This is essentially:
$teamname = null;
$teamname->find('a')->href;
The problem in your example is that $teamname is a string and you're treating it like a simple_html_dom_node

Xpath find a unique selector

I am looking to parse a html page for a predefined string and then build a unique reference to that location. With the help of 'Wikken' I have come this far.. but it is not working quite correctly.
$d = new DOMDocument();
$d->loadXML($xml);
$x = new DOMXPath($d);
$result = $x->evaluate("//text()[contains(.,'STRING')]/ancestor::*/#id");
$unique = null;
for($i = $result->length -1;$i >= 0 && $item = $result->item($i);$i--){
if($x->query("//*[#id='".addslashes($item->value)."']")->length == 1){
echo 'Unique ID is '.$item->value."\n";
$unique = $item->value;
break;
}
}
if(is_null($unique)) echo 'no unique ID found';
__EDIT_
Let me explain the problem again. I am looking to make a html parser that can parse a page and find a unique string. I then need to find a unique place holder for that location so that when the data on the website changes I can find the new data. Wrikken has helped me so far as to locating the string... unfortunately the code above does not find a unique css selector correctly.
Not sure if this is your problem, but I normally would do the first part more like this:
//*[contains(text(),'STRING')]/ancestor::*/#id

Categories