PHP OOP confusion for noobie - php

I have a problem that's born of being a dyed in the wool procedural programmer who's here forced into using some OOP constructs in order to make use of a library I need to use. I am stuck unable to access variables- other than print them out. Let me illustrate:
foreach($html->find('span[class="given-name"]') as $e)
echo $e->innertext . '<br>';
foreach($html->find('span[class="family-name"]') as $e)
echo $e->innertext . '<br>';
The above will print out a long list of first names, followed by a long list of surnames. However I want to be able to access them together. For example I want to be able to say something like $myarray["firstname"] = (*whatever is in $e->innertext*) and also $myarray["surnamename"] = (*whatever is in the next $e->innertext*)
When I try the seemingly obvious:
$x = $e->innertext;
it crashes. I assume that's because I am passing a pointer to $x instead of a value, but how on earth do I tell it I want the value - in this case a part of a person's name, to be assigned to $x, or my array, or whatever the variable might be?
I am almost a complete neophyte when it comes to OOP concepts and constructs, so please bear that in mind. Thank you for your assistance!

If your document is well structured and in order, this should do the trick:
$name=array();
$surname=array();
foreach($html->find('span[class="given-name"]') as $e){
$name[]=$e->innertext;
}
foreach($html->find('span[class="family-name"]') as $e){
$surname[]=$e->innertext;
}
foreach($name as $key=>$value){
echo $name[$key] . " " . $surname[$key] . "<br>";
}

Related

Open xml a php page

Good, again I ask your help, I have a xml file (http://radiojoven.6te.net/AirPlayHistory.xml) with several songs and I just wanted to take the song "I Need Your Love" from "SHAGGY "but I using a code I found here can not, appears all the songs. Could help me solve the problem?
<?php
$xml = simplexml_load_file("http://radiojoven.6te.net/AirPlayHistory.xml");
foreach($xml->Song as $item)
echo $item->Artist['name'] . " - " . $item['title'] ."<br>";
?>
Thanks!
I think what you are looking for a conditional control structures, namely if (I'm sorry if I'm something you already know). So inside your loop you can go:
foreach($xml->Song as $item) {
if ($item->Artist['name'] == 'SHAGGY' && $item['title'] == 'I NEED YOUR LOVE') {
echo $item->Artist['name'] . " - " . $item['title'] ."<br>";
}
}
(Sorry for the unrealistic example, you probably get the derails for the conditionals in variables).
There are other ways to query and filter things specific to XML documents, namely xpath that use can use as well.

PHP JSON Parsing Issue

I have this JSON output from a Government API, I need to display it using PHP. The problem is I can't use foreach more then once in a row or it doesn't work. I can't load all the criteria into the first foreach because say the first piece of data ACASS returns 3 results, all the fields after it will be displayed 3 times. Each field could return 1-10 results so there needs to be a system that accounts for variables.
I'm thinking the solution is to put all of the JSON items I need displayed into the first foreach but set them to only display if they're populated. That or use the current coding system I have but account for variable numbers somehow.
Any potential solutions are greatly appreciated.
This is the JSON output... https://api.data.gov/sam/v4/registrations/9606040070000?api_key=WI7nHENlp6QDMnWsb0Nnmzsv1slPDTjNM0XBoKvY
Here's the PHP I'm using...
echo "ACASS ID:".$decoded_results['sam_data']['registration']['qualifications']['acass']['id']."</br>";
foreach($decoded_results['sam_data']['registration']['qualifications']['acass']['answers'] as $acass)
{
echo 'Answer Text:'.$acass['answerText'].'</br>';
echo 'ACASS Section:'.$acass['section'].'</br>';
}
$formerfirm = $decoded_results['sam_data']['registration']['qualifications']['acass']['answers'][2]['FormerFirm'];
echo 'Former Firm ID:'.$formerfirm['id'].'</br>';
echo 'Former Firm Year Established:'.$formerfirm['yearEstablished'].'</br>';
echo 'Former Firm Name:'.$formerfirm['name'].'</br>';
echo 'Former Firm DUNS'.$formerfirm['duns'].'</br>';
I did my best to keep this short and simple question / code wise. In summary the issue is if you look at the JSON the data hierarchy makes a lot of the information display under ACASS/Answers and then the next category. I never know how many responses there will be and I'm not sure how to account for those variables.
I would like to thank everyone on these boards who has guided me as a new member and helped me post cleaner, more concise questions. Also thank you to everyone who has taken their own personal time to help me learn to become a better programmer.
use a tool like http://jsonviewer.stack.hu/ for visualizing your json structure. It helps a lot.
<?php
$url = "https://api.data.gov/sam/v4/registrations/9606040070000?api_key=WI7nHENlp6QDMnWsb0Nnmzsv1slPDTjNM0XBoKvY";
$contents = json_decode(file_get_contents($url));
// echo var_dump($contents);
$sam_data = $contents->sam_data;
// echo var_dump($sam_data);
$registration = $sam_data->registration;
//echo var_dump($registration);
$acass = $contents->sam_data->registration->qualifications->acass;
$id = $acass->id;
echo "id: ". $id . "<br />";
//echo var_dump($acass->answers);
foreach($acass->answers as $answer) {
if(isset($answer->FormerFirm)) {
$formerFirm = $answer->FormerFirm;
echo var_dump($formerFirm);
}
}

Simple_html_dom - Find first line only

I use Simple_html_dom and I want it to show the first span.muted it finds on the page.
foreach($html->find('span.muted') as $e)
echo $e->innertext . "<br>";
Currently it execute a list of all the span.muted, and can't really seems to make it work like I want it.
This is what it looks like when i use the code.
3.1
Version: 3.1
Version: 3.1
Version: 3.1
And only want it to show 3.1 in this example.
If you want to show only the first one it finds without modify much of your code. Maybe you can use break like this.
foreach($html->find('span.muted') as $e) {
echo $e->innertext . "<br>";
break;
}
Or you can simplify it to:
echo $html->find('span.muted')->innertext . "<br>";
If the result is accurate and you're looking to grab only the version number regardless of the text that precedes it, you could use regular expressions on the result:
foreach($html->find('span.muted') as $e)
if(preg_match('/\d+\.\d+$/', $e->innertext, $matches)) {
echo $matches[0] . '<br />';
}
}
It looks like this:
echo $html->find('span.muted', 0)->innertext;

Send MultipleIterator to an email

my english may be confusing, i'll try to be specific. It's about PHP, here in stackoverflow i found a piece of code that is so near to give me what i want (an answer of ValkerK), i have two arrays to iterate into one and i found an answer to a question that was exactly what i was lookin for. I just need to create a variable and send the prints to an e-mail. It may be simpliest but i'm not exactly an expert, here is the code if you can help me, thanks for reading this.
$want = new ArrayIterator($_POST['product']);
$amount = new ArrayIterator($_POST['howmany']);
$it = new MultipleIterator;
$it->attachIterator($want);
$it->attachIterator($amount);
foreach($it as $e) {
echo $e[0], ' : ', $e[1], ", ";
}
Then i have this prints
Product1:10, Product2:12, Product3:7.... etc
I need a variable to send that to an e-mail, but i still can't make it it work... thankes for your help.
Use something like this:
$contents = '';
foreach($it as $e) {
$contents .= $e[0] . ' : ' . $e[1] . ", ";
}
Now you can email $contents, which will contain the exact same output. You can also use output buffering, but for such a simple use-case, I wouldn't bother with it.
$var = implode("\n",array_map(function($v){
return $v[0]. ':'. $v[1].",";
}, $it));

Google Calendar/PHP newb question

I've been scouring around for information through the google Calendar API, the Zend docs, and here, and just about everything I find seems to make assumptions on what I already know about PHP, so I'm just getting more lost. I do have a good deal of programming experience... with... um... a FORTH variant. Anyway! I'm trying to pass the output of a PHP script that can be used to get all of the important data from a calendar event into said FORTH variant. What's driving me up the wall is that I can't figure out how to grab something as simple as the UID of a message. Here's what I'm working with:
function outputCalendar($client)
{
$gdataCal = new Zend_Gdata_Calendar($client);
$eventFeed = $gdataCal->getCalendarEventFeed();
foreach ($eventFeed as $event) {
echo $event->title->text . " (" . $event->id->text . ")\n";
foreach ($event->when as $when) {
echo $when->startTime . "\n";
}
}
}
This is based off the example code they gave me, and instead of formatting with with XML tags like in the example, just puts each on its own new line (which is easier for me to pull into the other language.)
Now, I tried to add echo $when->startTime . "\n"; to the loop, but it just tells me:
Fatal error: Uncaught exception 'Zend_Gdata_App_InvalidArgumentException' with message 'Property uid does not exist' in /var/mucktools/Zend/Gdata/App/Base.php:484
So, obviously, I'm going about grabbing the UID the wrong way. Now, here's the thing. These two lines:
echo $event->title->text . " (" . $event->id->text . ")\n";
echo $when->startTime . "\n";
...are pulling data from the event. However, 'title'. 'text', 'startTime' all look like things pulled out of one's posterior. I know, cognitively, that can't be true. There is a library and an API here. But I want to know where I can find a listing of all the crap I can pull out of $event and what the syntax is to do so. Can anyone help me with this?
And before you ask, yes, I have a very good reason to be grabbing the output of a PHP script and stuffing it into an obscure FORTH variant. And no, there's not another way that won't be more complicated than this one. I've done my homework here.
I'm sure you've read the documentation for Zend Gdata. It tells you that you need to provide getCalendarEventFeed() with a Zend_Gdata_Query object, otherwise I think you just get public data back.
Your code then should look something like this:-
$service = Zend_Gdata_Calendar::AUTH_SERVICE_NAME;
$user = "user#gmail.com";
$pass = "userpassword";
$client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $service);
$gDataCal = new Zend_Gdata_Calendar($client);
$query = $gDataCal->newEventQuery();
$query->setVisibility('private');
$query->setProjection('full');
$query->setOrderby('starttime');
$query->setFutureevents('true');
$eventFeed = $gDataCal->getCalendarEventFeed($query);
foreach ($eventFeed as $event) {
echo $event->title . " (" . $event->id . ")\n";
foreach($event->when as $when){
echo $when->startTime . "\n";
}
}
Hopefully that should get you started in the right direction.
Also the php_openSSL module has to be enabled in PHP for this to work, but I assume you have that already enabled to get as far as you did.

Categories