php XMLReader how to get particular item? - php

I create code for parse xml.and it is like this
<?php
$xmlDocument = '<?xml version="1.0"?>
<toys>
<toy code="10001">
<name>Ben 10 Watch</name>
<type>Battery Toys</type>
</toy>
<toy code="10002">
<name>Angry Birds Gun</name>
<type>Mechanical Toys</type>
</toy>
</toys>';
$xml = new XMLReader();
$xml->XML($xmlDocument);
while( $xml->read() ) {
if($xml->name == "toy") {
print "ID:" . $xml->getAttribute("code") . "<br/>";
print $xml->readInnerXML() . "<br/>";
$xml->next();
}
}
?>
which works fine with no problem and give the output as expected
ID:10001
Ben 10 Watch Battery Toys
ID:10002
Angry Birds Gun Mechanical Toys
now i want only one item to be seen in this or for huge xml file how to get one particular item.
for this i create code like this.
<?php
$xmlDocument = '<?xml version="1.0"?>
<toys>
<toy code="10001">
<name>Ben 10 Watch</name>
<type>Battery Toys</type>
</toy>
<toy code="10002">
<name>Angry Birds Gun</name>
<type>Mechanical Toys</type>
</toy>
</toys>';
$xml = new XMLReader();
$xml->XML($xmlDocument);
$xml->read(0);
$xml->name == "toy";
print "ID:" . $xml->getAttribute("code") . "<br/>";
print $xml->readInnerXML() . "<br/>";
?>
it does not as expected i want only one item to be printed.
how to do this .
summary of question is that how to get particular one item .

Change:
$xml->read(0);
$xml->name == "toy";
print "ID:" . $xml->getAttribute("code") . "<br/>";
print $xml->readInnerXML() . "<br/>";
to:
$xml->read();
$xml->read();
if($xml->name == "toy")
{
print "ID:" . $xml->getAttribute("code") . "<br/>";
print $xml->readInnerXML() . "<br/>";
}

Related

How to use foreach with PHP & XML

This is my php code
$xmldata = simplexml_load_string($ops_response);
foreach($xmldata->world-patent-data->biblio-search->search-result->exchange-documents->exchange-document->bibliographic-data->parties as $item)
{
echo "<p>Applicant Name: " . $item->applicants->applicant->applicant-name->name . "</p>";
echo "<p>Doc Number: " . $item->applicants->applicant->applicant-name->doc-number . "</p>";
echo "<p>Description: " . $item->applicants->applicant->applicant-name->abstract . "</p>";
}
This is my XML File:
https://ipappatent.com/xml/document.xml
Expected Result
<p>Applicant Name: PHYLION BATTERY CO LTD</p>
<p>Doc Number: 2018101613</p>
<p>Description: A frame tube having a battery enclosure structure for an electric bike. The frame tube comprises a main body</p>
<p>Year: ASTRO ENGINEERING CO LTD [TW]</p>
<p>Category: 20180821</p>
<p>Country: A drive assemblage is described for a vehicle drivable by muscle energy and/or—in particular additionally—by motor energy</p>
Iam new to PHP and i am not very well sure on how to handle the xml output? If anyone can help me on this pls do that. Appreciate your help.
libxml_use_internal_errors(true);
$myXMLData =
"<?xml version='1.0' encoding='UTF-8'?>
<document>
<user>John Doe</wronguser>
<email>john#example.com</wrongemail>
</document>";
$xml = simplexml_load_string($myXMLData);
if ($xml === false) {
echo "Failed loading XML: ";
foreach(libxml_get_errors() as $error) {
echo "<br>", $error->message;
}
} else {
print_r($xml);
}
?>
hi try like this
Do like this. You have passes object instead of array.
Json decode and encode simplexml_load_string($ops_response).
$string = //"your xml string here";
echo "<pre>";
$json = json_decode(json_encode((array) simplexml_load_string($string)), 1);
print_r($json);
$json = $json['biblio-search']['search-result']['exchange-documents'];
foreach($json as $item)
{
echo "<p>Applicant Name: " . $item['exchange-document']['bibliographic-data']['parties']['applicants']['applicant'][0]['applicant-name']['name'] . "</p>";
echo "<p>Description: " . $item['exchange-document']['abstract']['#attributes']['lang'] . "</p>";
}

Nested foreach when reading XML (in PHP)

I need to create a CRON job that are weekly going to read a XML file. The XML file contains information about all the shows at a range of cinemas.
What I want to do is to read the XML file, extract the information I need about each show, and then upload each show to a database. But I run into trouble when I start nesting the for-loops.
I want each tuple to contain the following information:
Tile | FilmWebNr | Rating | Version | Center | Screen | Date | Time |
The URL for the XML is http://217.144.251.113/static/Shows_FilmWeb.php
Here is a pastebin where I try to list all the dates for each screen per Title.
Here is the result. As you can see, the dates is only displayed when there are more than 1 screen per Title. I dont get why the attributes array isn't always available.
I struggle with getting the last three (screen, date and time).
$map_url = "http://217.144.251.113/static/Shows_FilmWeb.php";
$response_xml_data = file_get_contents($map_url);
$data = simplexml_load_string($response_xml_data);
$array = (array) simplexml_load_string($response_xml_data);
$json = json_encode($array);
$configData = json_decode($json, true);
$movies = $configData['Performances']['Title'];
foreach ($movies as $title) {
echo "Title: " . $title['#attributes']['Name'] . '<br/>';
echo "FilmWebNr: " . $title['FilmWebNum'] . '<br/>';
echo "Rating: " . $title['TitleRating'] . '<br/>';
echo "Version: " . $title['TitleVersion'] . '<br/>';
echo "Center: " . $title['Center']['#attributes']['Name'] . '<br/>';
foreach ($title['Center']['Screen'] as $screen) {
//here I run into trouble
}
}
Let say I try to add the following in the inner loop:
$screen['#attributes']['Name'];
I get an error saying "Undefined index: #attributes".
So sometimes the attributes seems to be in an array, but sometimes not. Even though It is always a part of the XML.
Rather than going from XML-JSON-Arrays, it may be better to learn how to work with SimpleXML and you will find it's quite easy.
The main thing is to get used to how the various elements are layered and use foreach loops to iterate over the blocks...
$map_url = "http://217.144.251.113/static/Shows_FilmWeb.php";
$response_xml_data = file_get_contents($map_url);
$data = simplexml_load_string($response_xml_data);
$movies = $data->Performances->Title;
foreach ($movies as $title) {
echo "Title: " . $title['Name'] . '<br/>';
echo "FilmWebNr: " . $title->FilmWebNum . '<br/>';
echo "Rating: " . $title->TitleRating . '<br/>';
echo "Version: " . $title->TitleVersion . '<br/>';
echo "Center: " . $title->Center['Name'] . '<br/>';
foreach ($title->Center->Screen as $screen) {
echo "screen:".$screen['Name']. '<br/>';
foreach ( $screen->Date as $date ) {
echo "Date:".$date['Name']. '<br/>';
foreach ( $date->ShowID as $showID ) {
echo "Time:".$showID->Time. '<br/>';
}
}
}
}

PHP (XML TO ARRAY) Getting the attribute of the xml that is array

Hello I am getting games in the spilgames xml. I managed to convert it to array but 1 problem came up again the problem is that the string I want to get is inside of an array or an attribute of 1 node xml .I can't get the attribute.
I want to get the attribute.
website of spilgames: here
Code I have so far:
<?php
$xml = simplexml_load_string(file_get_contents('http://publishers.spilgames.com/rss-3?limit=100&format=xml&category=Action')); /* Get the xml */
$json = json_encode($xml);
$games = json_decode($json); /* Make it an array */
$game = $games->entries->entry;
foreach($game as $entry) { /* Each game information */
echo $entry->title;
echo $entry->id;
echo $entry->description;
echo $entry->category;
echo $entry->subcategory;
echo $entry->technology;
echo $entry->player->url;;
echo $entry->thumbnails->small->url; /* Problems starts here */
/* Because the thumbnails has 3 child but the info is inside of each child */
}
?>
I am getting the xml not json in spilgames because I don't know how json works.
If I were you I would learn how JSON works because it will make your life easier:
<?php
$json = file_get_contents('http://publishers.spilgames.com/rss-3?limit=100&format=json&category=Action');
$data = json_decode($json);
foreach ($data->entries as $entry) {
echo $entry->title . "\n";
echo $entry->id . "\n";
echo $entry->description . "\n";
echo $entry->category . "\n";
echo $entry->subcategory . "\n";
echo $entry->technology . "\n";
echo $entry->thumbnails->small . "\n";
echo $entry->thumbnails->medium . "\n";
echo $entry->thumbnails->large . "\n";
}
?>

Getting XML with PHP: how to get attributes from 2 nodes with same name

I am getting attributes from XML nodes and saving them to variables with a for loop as such:
for ($i = 0; $i < 10; $i++){
$group = $xml->Competition->Round[0]->Event[$i][Group];
if($group == "MTCH"){
$eventid = $xml->Competition->Round[0]->Event[$i][EventID];
$eventname = $xml->Competition->Round[0]->Event[$i][EventName];
$teamaname = $xml->Competition->Round[0]->Event[$i]->EventSelections[0][EventSelectionName];
$teambname = $xml->Competition->Round[0]->Event[$i]->EventSelections[1][EventSelectionName];
echo "<br/>" . $eventid . ": " . $eventname . ", " . $teamaname . "VS" . $teambname;
}//IF
}//FOR
I can save each Event[EventID] and each Event[EventName] but I cannot get the EventSelections[EventSelectionNames] to save.
I am guessing this is because there are multiple (2) <EventSelection>s for each <Event>, this is why I tried to get them individually uising [0] and [1].
The part of the XML file in question looks like:
<Event EventID="1008782" EventName="Collingwood v Fremantle" Venue="" EventDate="2014-03-14T18:20:00" Group="MTCH">
<Market Type="Head to Head" EachWayPlaces="0">
<EventSelections BetSelectionID="88029974" EventSelectionName="Collingwood">
<Bet Odds="2.10" Line=""/>
</EventSelections>
<EventSelections BetSelectionID="88029975" EventSelectionName="Fremantle">
<Bet Odds="1.70" Line=""/>
</EventSelections>
</Market>
</Event>
Can anyone point me in the right direction to save the EventSelectionNames to variables?
Rather than looping and checking for $group, use xpath to select data directly:
$xml = simplexml_load_string($x); // assume XML in $x
$group = $xml->xpath("/Event[#Group = 'MTCH']")[0];
echo "ID: $group[EventID], name: $group[EventName]" . PHP_EOL;
If there are always two <EventSelections>, you can:
echo "Team A: " . $group->Market->EventSelections[0]['EventSelectionName']" . PHP_EOL;
echo "Team B: " . $group->Market->EventSelections[1]['EventSelectionName']" . PHP_EOL;
Otherwise, use foreach:
foreach ($group->Market->EventSelections as $es)
$teamnames[] = $es['EventSelectionName'];
echo "There are " . count($teamnames) . "Teams:" . PHP_EOL;
foreach ($teamname as $teamname) echo $teamname . PHP_EOL;
see it in action: https://eval.in/105642
Note:
The [0] at the end of the code-line starting with $group = $xml->xpath...requires PHP >= 5.4. If you are on a lower version, update PHP or use:
$group = $xml->xpath("/Event[#Group = 'MTCH']");
$group = $group[0];
Michi's answer is more correct and better coded but I also found the adding the node 'Market' to my code worked as well:
$teamaname = $xml->Competition->Round[0]->Event[$i]->Market->EventSelections[0][EventSelectionName];
$teambname = $xml->Competition->Round[0]->Event[$i]->Market->EventSelections[1][EventSelectionName];

How to parse XML using PHP

I've this code
$xml = simplexml_load_file("http://api.hostip.info/?ip=12.215.42.19");
echo $xml->getName() . "<br />";
foreach($xml->children() as $child) {
echo $child->getName() . ": " . $child . "<br />";
}
If I visit http://api.hostip.info/?ip=12.215.42.19 directly on the browser, I can see the XML return but when I tried the above code, only HostipLookupResultSet<br /> gets echoed.
How do I retrieve the data from this xml? I'm interested in getting coutry and country abbreviation.
I was trying something like echo $xml->HostipLookupResultSet->gml:featureMember->Hostip->countryName but it seems it is wrong.
This might work if you query using xpath :-
// optional for register namespace into xpath
$xml->registerXPathNamespace('gml', 'http://www.opengis.net/gml');
$result = $xml->xpath('//*[self::countryName or self::countryAbbrev]');
You need to add the namespace.
See the code bellow
/* #var $xml SimpleXMLElement */
echo $xml->getName() . "\n";
$namespaces = $xml->getDocNamespaces();
foreach($xml->children($namespaces['gml']) as $child) {
echo $child->getName() . ": " . $child . "\n";
}
You can try the following code for getting Country and Country Abbrevation:
$xml = simplexml_load_file("http://api.hostip.info/?ip=12.215.42.19");
$cntry= $xml->xpath('//gml:featureMember');
foreach($cntry as $child) {
echo $child->Hostip->countryName;
echo "<br />";
echo $child->Hostip->countryAbbrev;
}

Categories