How to use foreach with PHP & XML - php

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>";
}

Related

php XMLReader how to get particular item?

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/>";
}

XML feeds and namespaces with PHP, SimpleXML and Xpath

Hi I have been struggling with this puzzle for some time now how to get data out of this embedded namespaces here is the xml feed I have cut it down to make easier to read
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns:atom="http://www.w3.org/2005/Atom" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:cf="http://www.microsoft.com/schemas/rss/core/2005" xmlns="http://www.w3.org/2005/Atom" xmlns:sc="http://schemas.sage.com/sc/2009" xmlns:crm="http://schemas.sage.com/crmErp/2008" xmlns:sdatasync="http://schemas.sage.com/sdata/sync/2008/1" xmlns:sdata="http://schemas.sage.com/sdata/2008/1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:opensearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:sme="http://schemas.sage.com/sdata/sme/2007" xmlns:http="http://schemas.sage.com/sdata/http/2008/1">
<author />
<category term="tradingAccount" />
<generator />
<subtitle>Provides a feed containing tradingAccount details</subtitle>
<title>Sage Accounts 50 | tradingAccount - Practice Accounts </title>
<entry>
<author />
<content type="html"><![CDATA[<html>
</html>]]></content>
<id>http://computer_1:5493/sdata/accounts50/GCRM/{FF476636-D4AF-4191-BDE4-891EDA349A68}/tradingAccountCustomer(58b10585-63d4-4bb8-adb3-7096d9b055d9)?format=atomentry</id>
<link href="http://computer_1:5493/sdata/accounts50/GCRM/-/tradingAccountCustomer" rel="via" type="application/atom+xml" />
<published>2015-03-13T21:28:59.000+00:00</published>
<updated>2015-07-01T21:33:13.000+01:00</updated>
<http:httpStatus>200</http:httpStatus>
<sdata:payload>
<crm:tradingAccount sdata:url="http://computer_1:5493/sdata/accounts50/GCRM/{FF476636-D4AF-4191-BDE4-891EDA349A68}/tradingAccountCustomer(58b10585-63d4-4bb8-adb3-7096d9b055d9)?format=atomentry" sdata:uuid="58b10585-63d4-4bb8-adb3-7096d9b055d9">
<crm:active>true</crm:active>
<crm:customerSupplierFlag>Customer</crm:customerSupplierFlag>
<crm:companyPersonFlag>Company</crm:companyPersonFlag>
<crm:invoiceTradingAccount xsi:nil="true" />
<crm:openedDate>2013-04-22</crm:openedDate>
<crm:reference>AAA</crm:reference>
<crm:name>BBB</crm:name>
</crm:tradingAccount>
</sdata:payload>
</entry>
<opensearch:totalResults>118</opensearch:totalResults>
<opensearch:startIndex>1</opensearch:startIndex>
<opensearch:itemsPerPage>118</opensearch:itemsPerPage>
</feed>
I am trying to access the <crm:reference><crm:name><crm:openedDate> namespace but failing I have looked at similar projects but I think its a namespace within a namespace
here is my attempt at parsing the data
<?php
$xml = simplexml_load_file("sage.xml");
$xml->registerXPathNamespace('sdata', 'http://schemas.sage.com/sdata/sync/2008/1');
foreach($xml->xpath("//sdata:payload") as $entry) {
$entry->registerXPathNamespace('sdata', 'http://schemas.sage.com/sdata/sync/2008/1');
$entry->registerXPathNamespace('crm', 'http://schemas.sage.com/crmErp/2008');
$content = $entry->xpath("/sdata:payload/crm:tradingAccount/crm:active");
//$article = feed->xpath("/sdata:payload/crm:tradingAccount/crm:active");
foreach($content as $c) {
// echo $c->reference . " | " . $c->name . "/" . $c->accountOpenedDate . "<br />\n";
}
}
var_dump($content);
var_dump($c);
any pointers to my problem would help
foreach($xml->xpath("//sdata:payload") as $entry) {
// xpath here must be from payload to tradingAccount
$content = $entry->xpath("./crm:tradingAccount");
foreach($content as $c) {
// Make set of children with prefix crm
$nodes = $c->children('crm', true);
echo $nodes->reference . " | " . $nodes->name . " / " . $nodes->openedDate . "<br />\n";
}
}
It could be as simple as:
$xml = simplexml_load_file("sage.xml");
$reference = $xml->xpath("//crm:reference");
$name = $xml->xpath("//crm:name");
$openedDate = $xml->xpath("//crm:openedDate");
echo "reference: ". $reference[0] . "<br>";
echo "name: ". $name[0] . "<br>";
echo "openedDate: ". $openedDate[0] . "<br>";
If you would like to use a foreach loop to get all children of 'crm' you can do the following. You need atleast 5.2.0 if you want to set children to prefix (true)
$xml = simplexml_load_file("sage.xml");
foreach($xml->xpath("//crm:tradingAccount") as $entry) {
$child = $entry->children('crm', true);
}
echo "reference: ". $child->reference . "<br>";
echo "name: ". $child->name . "<br>";
echo "openedDate: ". $child->openedDate . "<br>";

PHP Parser Using simplexml_load_string() [duplicate]

This question already has answers here:
Using SimpleXML to read RSS feed
(2 answers)
Closed 8 years ago.
This is a beginners question (sorry for that); I am using simplexml_load_string() php function to parse an RSS feed, my code looks like this:
<?php
$url = "http://www.zdnet.com/blog/rss.xml";
$xml = file_get_contents($url);
$feed = simplexml_load_string($xml);
foreach($feed->channel as $channel) {
echo "Link : " . $channel->link . "<P>";
echo "Image URL : " . $channel->image->url . "<P>";
}
foreach($feed->channel->item as $item) {
echo "<HR><P>";
echo "Link : " . $item->link . "<P>";
echo "Title : " . $item->title . "<P>";
echo "Description : " . $item->description . "<P>";
echo "Date : " . $item->pubDate . "<P>";
}
?>
Which is working fine but the XML file has some tags that look like this:
<media:credit role="author">
<![CDATA[ James Kendrick ]]>
</media:credit>
<media:text type="html">
<![CDATA[
<figure class="alignRight"><a href="/i/story/70/00/034218/kindle-iphone-2.jpg" target="_blank">
<img title="kindle-iphone-2" alt="kindle-iphone-2" src="http://cdn-static.zdnet.com/1.jpg">
height="237" width="200"></a><figcaption>(I
]]>
<![CDATA[
mage: James Kendrick/ ZDNet)</figcaption></figure> <p>Regular readers know I am a tablet guy
]]>
</media:text>
How can I parse these tags?
Thanks
For accessing that nodes with namespaces you could use ->children() in that case:
$url = "http://www.zdnet.com/blog/rss.xml";
$feed = simplexml_load_file($url, null, LIBXML_NOCDATA);
foreach($feed->channel->item as $item) {
echo "<HR><P>";
echo "Link : " . $item->link . "<P>";
echo "Title : " . $item->title . "<P>";
echo "Description : " . $item->description . "<P>";
echo "Date : " . $item->pubDate . "<P>";
$media = $item->children('media', 'http://search.yahoo.com/mrss/'); // medias
// then just loop the children
// foreach($media as $m) {}
$s = $item->children('s', 'http://www.zdnet.com/search'); // ss
}

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";
}
?>

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