There are several tags in the xml file. How can I find an tag with the content in "BRL"?
i have tried
$usd_brazilRate = $usdXML->item[89]->title;<br>
$usd_brazilDate = $usdXML->item[89]->pubDate;<br>
but the item number (position) always changes
example cropped xml content:
<channel>
<item>
<title>1 USD = 64.78833120 RUB</title>
<link>http://www.floatrates.com/usd/rub/</link>
<description>1 U.S. Dollar = 64.78833120 Russian Rouble</description>
<pubDate>Thu, 2 May 2019 12:00:02 GMT</pubDate>
<baseCurrency>USD</baseCurrency>
<baseName>U.S. Dollar</baseName>
<targetCurrency>RUB</targetCurrency>
<targetName>Russian Rouble</targetName>
<exchangeRate>64.78833120</exchangeRate>
<inverseRate>0.01543488</inverseRate>
<inverseDescription>1 Russian Rouble = 0.01543488 U.S. Dollar</inverseDescription>
</item>
<item>
<title>1 USD = 3.92245587 BRL</title>
<link>http://www.floatrates.com/usd/brl/</link>
<description>1 U.S. Dollar = 3.92245587 Brazilian Real</description>
<pubDate>Thu, 2 May 2019 12:00:02 GMT</pubDate>
<baseCurrency>USD</baseCurrency>
<baseName>U.S. Dollar</baseName>
<targetCurrency>BRL</targetCurrency>
<targetName>Brazilian Real</targetName>
<exchangeRate>3.92245587</exchangeRate>
<inverseRate>0.25494232</inverseRate>
<inverseDescription>1 Brazilian Real = 0.25494232 U.S. Dollar</inverseDescription>
</item>
<item>
<title>1 USD = 0.76733706 GIP</title>
<link>http://www.floatrates.com/usd/gip/</link>
<description>1 U.S. Dollar = 0.76733706 Gibraltar pound</description>
<pubDate>Thu, 2 May 2019 12:00:02 GMT</pubDate>
<baseCurrency>USD</baseCurrency>
<baseName>U.S. Dollar</baseName>
<targetCurrency>GIP</targetCurrency>
<targetName>Gibraltar pound</targetName>
<exchangeRate>0.76733706</exchangeRate>
<inverseRate>1.30320826</inverseRate>
<inverseDescription>1 Gibraltar pound = 1.30320826 U.S. Dollar</inverseDescription>
</item>
</channel>
$usdXML = simplexml_load_file("http://www.floatrates.com/daily/usd.xml") or die("Failed to load");
$usd_brazilRate = $usdXML->item->title;
$usd_brazilDate = $usdXML->item->pubDate;
output
1 USD = 3.92245587 BRL
Thu, 2 May 2019 12:00:02 GMT
You can use XPath:
$brazil = $usdXML->xpath('/channel/item[targetCurrency="BRL"]');
print($brazil[0]->description . "\n");
print($brazil[0]->pubDate . "\n");
This is my code:
<?php
include('simple_html_dom.php');
$html = file_get_html('http://www.google.com/search?q=BA236',false);
$title=$html->find('div#ires', 0)->innertext;
echo $title;
?>
It outputs all result of the Google Search Page under the Search "BA236".
The problem is I dont need all of them and the Information I need is inside a div that has no id or class or anything else.
The div I need is inside the first
<div class="g">
on the Page, so maybe I should try something like this:
<?php
include('simple_html_dom.php');
$html = file_get_html('http://www.google.com/search?q=BA236',false);
$title=$html->find('div[class=g], 0')->innertext;
echo $title;
?>
But the Problem of that is, if I load the page it shows me nothing except this:
Notice: Trying to get property of non-object in
C:\xampp\htdocs...\simpletest2.php on line 4
So how can i get the div i´m searching for and what am I doing wrong ?
Edit:
Solution:
<?php
include('simple_html_dom.php');
$html = file_get_html('http://www.google.com/search?q=BA236',false);
$e = $html->find("div[class=g]");
echo $e[0]->innertext;
?>
Or:
<?php
include('simple_html_dom.php');
$html = file_get_html('http://www.google.com/search?q=BA236',false);
$title=$html->find('div[class=g]')[0]->innertext;
echo $title;
?>
I made a change to your code where I am searching for the class:
<?php
include('simple_html_dom.php');
$html = file_get_html('http://www.google.com/search?q=BA236',false);
$e = $html->find("div[class=g]");
echo $e[0]->innertext;
?>
result:
British Airways Flight 236
Scheduled departs in 13 hours 13 mins
Departure DME 5:40 AM —
Moscow Dec 15
Arrival LHR 6:55 AM Terminal 5
London Dec 15
Scheduled departs in 1 day 13 hours
Departure DME 5:40 AM —
Moscow Dec 16
Arrival LHR 6:55 AM Terminal 5
London Dec 16
I looked for the div elements with class g then I printed the count of the first element '0'
$e = $html-> find ("div [class = g]");
echo $e [0]->innertext;
Your code:
<?php
include('simple_html_dom.php');
$html = file_get_html('http://www.google.com/search?q=BA236',false);
$title=$html->find('div[class=g]')[0]->innertext;
echo $title;
?>
not ('div[class=g], 0')
but ('div[class=g]')[0]
there is no need for simple_html_dom here, it's easy to do with the builtins DOMDocument and DOMXPath.
<?php
$html = file_get_contents('http://www.google.com/search?q=BA236');
echo (new DOMXPath ( (#DOMDocument::loadHTML ( $html )) ))->query ( '//div[#class="g"]' )->item ( 0 )->textContent;
in my opinion, DOMDocument + DOMXPath makes simple_html_dom.php rather pointless. the former 2 can do pretty much everything simple_html_dom can do, and are built-in native php functions, which is likely to be maintained as long as PHP itself is maintained, and the latter is a 3rd party project which seems nearly dead by the looks of it (last commit was in 2014, there was only 1 commit in all of 2014, and 2 commits in all of 2013 )
Hi i need help to get all categories from rss.
This is ex. of my rss feed:
<item>
<title>Coca-Cola</title>
<link>https://www.tralaaa.com/coca-cola/</link>
<comments></comments>
<pubDate>Fri, 01 Dec 2017 11:36:40 +0000</pubDate>
<dc:creator><![CDATA[Admin]]></dc:creator>
<category><![CDATA[cat1]]></category>
<category><![CDATA[cat2]]></category>
<category><![CDATA[cat3]]></category>
<category><![CDATA[cat4]]></category>
<description><![CDATA[]]></description>
<content:encoded><![CDATA[]]></content:encoded>
</item>
I try with $cat = $item->category(0); but give me the error
Call to undefined method SimpleXMLElement::category()
You cant access category using () parenthesis, you need to use [], like this:
$xml = new SimpleXMLElement(
'<item>
<title>Coca-Cola</title>
<link>https://www.tralaaa.com/coca-cola/</link>
<comments></comments>
<pubDate>Fri, 01 Dec 2017 11:36:40 +0000</pubDate>
<dc:creator><![CDATA[Admin]]></dc:creator>
<category><![CDATA[cat1]]></category>
<category><![CDATA[cat2]]></category>
<category><![CDATA[cat3]]></category>
<category><![CDATA[cat4]]></category>
<description><![CDATA[]]></description>
<content:encoded><![CDATA[]]></content:encoded>
</item>');
$cat_name1 = $xml->category[0]->__toString();
$cat_name2 = $xml->category[1]->__toString();
$cat_name3 = $xml->category[2]->__toString();
$cat_name4 = $xml->category[3]->__toString();
echo "<pre>";
print_r($cat_name1);
echo "</pre>";
echo "<pre>";
print_r($cat_name2);
echo "</pre>";
echo "<pre>";
print_r($cat_name3);
echo "</pre>";
echo "<pre>";
print_r($cat_name4);
echo "</pre>";
this will output:
you can just:
$xml->category->__toString();
it will assume you want the first category.
This is my xml file which I'm trying to parse using PHP simplexml_load_string() function class but it only print </description> tag and rest of the xml is not returned
XML file:
<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dcterms="http://purl.org/dc/terms/" xmlns:dfpvideo="http://api.google.com/dfpvideo" xmlns:media="http://search.yahoo.com/mrss/" xmlns:ngc="http://xml.natgeotv.com/fields" xmlns:ngs="http://prod.ngs.org/ngs" xmlns:ngsDebug="http://prod.ngs.org/ngs-debug" xmlns:ngsTax="http://prod.ngs.org/taxonomy" xmlns:os="http://a9.com/-/spec/opensearch/1.1/" xmlns:pl="http://xml.theplatform.com/data/object" xmlns:pl1="http://access.auth.theplatform.com/data/Account/2388557369" xmlns:pl2="http://access.auth.theplatform.com/data/Account/2423130747" xmlns:pla="http://xml.theplatform.com/data/object/admin" xmlns:plfile="http://xml.theplatform.com/media/data/MediaFile" xmlns:pllist="http://xml.theplatform.com/data/list" xmlns:plmedia="http://xml.theplatform.com/media/data/Media" xmlns:plrelease="http://xml.theplatform.com/media/data/Release" xmlns:wpf="http://prod.ngs.org/wpf" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ytcp="http://www.youtube.com/schemas/cms/2.0" version="2.0">
<channel>
<title>NG Video</title>
<link>http://feed.theplatform.com/f/ngs/dCCn2isYZ9N9</link>
<description>NG Video</description>
<os:startIndex>1</os:startIndex>
<os:itemsPerPage>100</os:itemsPerPage>
<pllist:entryCount>1</pllist:entryCount>
<item>
<pl:id>http://data.media.theplatform.com/media/data/Media/97681476000</pl:id>
<guid isPermaLink="false">a4ad87f6-cbe4-4816-9580-b6679af0ea73</guid>
<title>NG Live!: Sheikh of the Arctic</title>
<description><p>Having completed more solo trips to the Poles than anyone else on the planet, Børge Ousland is sometimes surprised by who he runs into crossing the vast Arctic tundra.</p></description>
<author />
<media:keywords />
<media:restriction relationship="deny" type="country" />
<media:content channels="2" samplingrate="44.1" bitrate="535.928" medium="video" duration="175.031" expression="full" fileSize="11725511" framerate="29.97" type="video/mp4" height="346" isDefault="true" url="http://link.theplatform.com/s/ngs/ekLOLGt3bemU?feed=NG%20Video" width="616">
<media:hash algo="md5">0AF4AD25977BF50888075D3547F67173</media:hash>
<pl:added>Sun, 22 Dec 2013 02:41:46 GMT</pl:added>
<plfile:assetType>mpeg4</plfile:assetType>
</media:content>
<media:thumbnail expression="full" fileSize="79478" type="image/jpeg" height="556" isDefault="false" url="http://pmdvod.nationalgeographic.com/NG_Video/997/323/67322_1_1280x720_990x556_177596483623.jpg" width="990">
<media:hash algo="md5">60FFCE1C849440050CBCBD259EF2CE65</media:hash>
<pl:added>Sun, 02 Mar 2014 05:26:41 GMT</pl:added>
<plfile:assetType>Poster</plfile:assetType>
<plfile:assetType>MED</plfile:assetType>
</media:thumbnail>
<media:thumbnail expression="full" fileSize="209762" type="image/jpeg" height="720" isDefault="false" url="http://pmdvod.nationalgeographic.com/NG_Video/997/323/67322_1_1280x720.jpg" width="1280">
<media:hash algo="md5">08AC83096DC5F7E48A7CDE4BFA23A27A</media:hash>
<pl:added>Sun, 02 Mar 2014 05:26:30 GMT</pl:added>
<plfile:assetType>Mezzanine Image</plfile:assetType>
</media:thumbnail>
<media:thumbnail expression="full" fileSize="2962" type="image/jpeg" height="68" isDefault="false" url="http://pmdvod.nationalgeographic.com/NG_Video/997/323/67322_1_1280x720_120x68_177597507564.jpg" width="120">
<media:hash algo="md5">605D86F9A2B606D97A653576E6CE99D2</media:hash>
<pl:added>Sun, 02 Mar 2014 05:26:45 GMT</pl:added>
<plfile:assetType>Thumbnail</plfile:assetType>
</media:thumbnail>
<media:thumbnail expression="full" fileSize="23707" type="image/jpeg" height="270" isDefault="false" url="http://pmdvod.nationalgeographic.com/NG_Video/997/323/67322_1_1280x720_480x270_177598019578.jpg" width="480">
<media:hash algo="md5">73F78D0314E0CC15CDA5C36AAE4560AD</media:hash>
<pl:added>Sun, 02 Mar 2014 05:26:42 GMT</pl:added>
<plfile:assetType>Poster</plfile:assetType>
<plfile:assetType>X-SM</plfile:assetType>
</media:thumbnail>
<media:thumbnail expression="full" fileSize="83905" type="image/jpeg" height="576" isDefault="false" url="http://pmdvod.nationalgeographic.com/NG_Video/997/323/67322_1_1280x720_1024x576_177598019579.jpg" width="1024">
<media:hash algo="md5">5C4B05CE487697A63F4FEC8B51009497</media:hash>
<pl:added>Sun, 02 Mar 2014 05:26:43 GMT</pl:added>
<plfile:assetType>Poster</plfile:assetType>
<plfile:assetType>LG</plfile:assetType>
</media:thumbnail>
<media:thumbnail expression="full" fileSize="114846" type="image/jpeg" height="720" isDefault="false" url="http://pmdvod.nationalgeographic.com/NG_Video/997/323/67322_1_1280x720_1280x720_177598019580.jpg" width="1280">
<media:hash algo="md5">31BFBD1020B2277B7E6FDD353973F263</media:hash>
<pl:added>Sun, 02 Mar 2014 05:26:43 GMT</pl:added>
<plfile:assetType>Poster</plfile:assetType>
<plfile:assetType>X-LG</plfile:assetType>
</media:thumbnail>
<media:thumbnail expression="full" fileSize="37132" type="image/jpeg" height="360" isDefault="true" url="http://pmdvod.nationalgeographic.com/NG_Video/997/323/67322_1_1280x720_640x360_177598019582.jpg" width="640">
<media:hash algo="md5">2654AFBE193785E29FF0533CF977A473</media:hash>
<pl:added>Sun, 02 Mar 2014 05:26:44 GMT</pl:added>
<plfile:assetType>Poster</plfile:assetType>
<plfile:assetType>SM</plfile:assetType>
</media:thumbnail>
<pubDate>Sat, 21 Dec 2013 06:56:49 GMT</pubDate>
<plmedia:defaultThumbnailUrl>http://pmdvod.nationalgeographic.com/NG_Video/997/323/67322_1_1280x720_640x360_177598019582.jpg</plmedia:defaultThumbnailUrl>
<plmedia:provider />
<pl1:youTubeInStreamStandard>true</pl1:youTubeInStreamStandard>
<pl1:youTubeInStreamTrueView>true</pl1:youTubeInStreamTrueView>
<pl1:youTubeInVideo>true</pl1:youTubeInVideo>
<pl1:youTubePublic>false</pl1:youTubePublic>
<ngs:clipTypeOld>none</ngs:clipTypeOld>
<ngs:contentCreationDate>Mon, 13 May 2013 19:03:22 GMT</ngs:contentCreationDate>
<ngs:network>NGS</ngs:network>
<ngs:redirectToExternal>never</ngs:redirectToExternal>
<ngs:requiresAuth>false</ngs:requiresAuth>
<ngs:series>{"updated_datetime":null,"creation_datetime":null,"is_active":false,"name":"National Geographic Live","translated_names":[],"synonyms":[],"uuid":null,"notes":null,"objectType":"org.ngs.video.Show","groups":[],"url":null}</ngs:series>
<ngs:seriesName>National Geographic Live</ngs:seriesName>
<ngsTax:location>{"updated_datetime":"2014-04-03T19:09:42.570Z","is_active":true,"creation_datetime":"2013-11-28T20:27:32.077Z","parent":"http://taxonomy.nationalgeographic.com/api/v1/locations/eea9ad49-32fc-3a7c-bf15-cfeabdaa2fb7","geonames_uri":null,"url":"http://taxonomy.nationalgeographic.com/api/v1/locations/ff4e742f-46e6-3867-be8c-003a7af8f86c","dbpedia_uri":"http://dbpedia.org/page/Arctic","name":"Arctic","longitude":0.0,"hierarchy":"earth/arctic/","latitude":0.0,"uuid":"ff4e742f-46e6-3867-be8c-003a7af8f86c","notes":"","objectType":"org.ngs.taxonomy.GeoLocation","groups":["Place","region"],"english_name":null,"parentName":"Earth"}</ngsTax:location>
<ngsTax:location>{"updated_datetime":"2014-05-28T20:43:43.719Z","is_active":true,"creation_datetime":"2013-11-28T20:01:26.936Z","synonyms":[null,null],"parent":"http://taxonomy.nationalgeographic.com/api/v1/locations/eea9ad49-32fc-3a7c-bf15-cfeabdaa2fb7","geonames_uri":"http://sws.geonames.org/6697173/","url":"http://taxonomy.nationalgeographic.com/api/v1/locations/d2ce52aa-c6ac-3a13-9f8c-59cb13ecb924","dbpedia_uri":null,"name":"Antarctica","translated_names":[null],"longitude":16.40626,"hierarchy":"earth/antarctica/","latitude":-78.15856,"uuid":"d2ce52aa-c6ac-3a13-9f8c-59cb13ecb924","notes":"","objectType":"org.ngs.taxonomy.GeoLocation","groups":["Place","continent"],"english_name":null,"parentName":"Earth"}</ngsTax:location>
<ngsTax:organization>{"updated_datetime":"2014-05-02T15:37:25.776Z","creation_datetime":"2013-11-28T19:40:52.694Z","is_active":true,"name":"National Geographic Live","synonyms":[null],"uuid":"bae34d69-0601-342b-abe4-345c4c2486c4","notes":"","objectType":"org.ngs.taxonomy.Organization","english_name":null,"groups":["Organization"],"url":"http://taxonomy.nationalgeographic.com/api/v1/organizations/bae34d69-0601-342b-abe4-345c4c2486c4"}</ngsTax:organization>
<ngsTax:slug>ousland-sheikh-bonus-nglive</ngsTax:slug>
<ngsTax:subject>{"updated_datetime":"2014-06-04T15:56:21.047Z","definition":"","is_active":true,"creation_datetime":"2013-11-28T19:59:40.956Z","scope_note":"","synonyms":[null],"parent":"http://taxonomy.nationalgeographic.com/api/v1/subjects/83bf00d5-93bd-3cca-acc3-543652f06d52","url":"http://taxonomy.nationalgeographic.com/api/v1/subjects/58f9272e-f37b-3550-a228-a5ee119553ae","name":"Explorers","hierarchy":"exploration/explorers/","uuid":"58f9272e-f37b-3550-a228-a5ee119553ae","notes":"","objectType":"org.ngs.taxonomy.Subject","groups":["Subject"],"english_name":null,"parentName":"Exploration"}</ngsTax:subject>
<ngsTax:subject>{"updated_datetime":"2014-01-29T14:56:08.338Z","definition":"","is_active":true,"creation_datetime":"2013-11-28T19:52:45.402Z","scope_note":"","parent":"http://taxonomy.nationalgeographic.com/api/v1/subjects/83bf00d5-93bd-3cca-acc3-543652f06d52","url":"http://taxonomy.nationalgeographic.com/api/v1/subjects/83c5f238-8dbc-373e-9d62-4deb4c59e122","name":"Expeditions","hierarchy":"exploration/expeditions/","uuid":"83c5f238-8dbc-373e-9d62-4deb4c59e122","notes":"","objectType":"org.ngs.taxonomy.Subject","groups":["Subject"],"english_name":null,"parentName":"Exploration"}</ngsTax:subject>
<ngsTax:subject>{"updated_datetime":"2014-02-10T19:47:37.384Z","definition":"","is_active":true,"creation_datetime":"2014-01-16T17:48:21.375Z","scope_note":"","synonyms":[null,null,null],"parent":"http://taxonomy.nationalgeographic.com/api/v1/subjects/a817863e-de0f-3ffd-944d-c75ed20308ff","url":"http://taxonomy.nationalgeographic.com/api/v1/subjects/f0c33fd8-5e31-36b2-9229-b71628df3367","name":"Travel","hierarchy":"travel-and-adventure/travel/","uuid":"f0c33fd8-5e31-36b2-9229-b71628df3367","notes":"","objectType":"org.ngs.taxonomy.Subject","groups":["Subject"],"english_name":null,"parentName":"Travel and Adventure"}</ngsTax:subject>
<ngsTax:title>NG Live!: Sheikh of the Arctic</ngsTax:title>
<wpf:allTaxonomyId>18160</wpf:allTaxonomyId>
<wpf:allTaxonomyId>1589</wpf:allTaxonomyId>
<wpf:allTaxonomyId>858</wpf:allTaxonomyId>
<wpf:altLinkedLegacyUrl />
<wpf:author />
<wpf:firstPublishedTime>Mon, 13 May 2013 19:11:17 GMT</wpf:firstPublishedTime>
<wpf:id>13615</wpf:id>
<wpf:lastPublishedTime>Mon, 03 Feb 2014 21:50:20 GMT</wpf:lastPublishedTime>
<wpf:lineupName>Nat Geo Live 2</wpf:lineupName>
<wpf:locationMigration>Arctic</wpf:locationMigration>
<wpf:locationMigration>Antarctica</wpf:locationMigration>
<wpf:metaKeyword>Nat Geo Live</wpf:metaKeyword>
<wpf:metaKeyword>Nat Geo Live!</wpf:metaKeyword>
<wpf:metaKeyword>lecture</wpf:metaKeyword>
<wpf:metaKeyword>National Geographic Live</wpf:metaKeyword>
<wpf:metaKeyword>National Geographic Live!</wpf:metaKeyword>
<wpf:metaKeyword>NGLive</wpf:metaKeyword>
<wpf:metaKeyword>NG Live</wpf:metaKeyword>
<wpf:metaKeyword>Nat Geo Events</wpf:metaKeyword>
<wpf:metaKeyword>Børge Ousland</wpf:metaKeyword>
<wpf:metaKeyword>polar</wpf:metaKeyword>
<wpf:metaKeyword>adventure</wpf:metaKeyword>
<wpf:metaKeyword>explore</wpf:metaKeyword>
<wpf:metaKeyword>exploration</wpf:metaKeyword>
<wpf:metaKeyword>expedition</wpf:metaKeyword>
<wpf:metaKeyword>ski</wpf:metaKeyword>
<wpf:metaKeyword>North Pole</wpf:metaKeyword>
<wpf:metaKeyword>loneliness</wpf:metaKeyword>
<wpf:metaKeyword>strange</wpf:metaKeyword>
<wpf:metaKeyword>visitor</wpf:metaKeyword>
<wpf:metaKeyword>ice</wpf:metaKeyword>
<wpf:metaKeyword>photo</wpf:metaKeyword>
<wpf:metaKeywords>Nat Geo Live, Nat Geo Live!, lecture, National Geographic Live, National Geographic Live!, NGLive, NG Live, Nat Geo Events, Børge Ousland, polar, adventure, explore, exploration, expedition, ski, North Pole, loneliness, strange, visitor, ice, photo</wpf:metaKeywords>
<wpf:organizationMigration>National Geographic Live</wpf:organizationMigration>
<wpf:sitePath>Specials Video::Nat Geo Live::Nat Geo Live 2</wpf:sitePath>
<wpf:siteUrlPath>/video/specials/nat-geo-live-specials/nat-geo-live-2/ousland-sheikh-bonus-nglive/</wpf:siteUrlPath>
<wpf:subjectMigration>Explorers</wpf:subjectMigration>
<wpf:subjectMigration>Expeditions</wpf:subjectMigration>
<wpf:subjectMigration>Travel</wpf:subjectMigration>
<wpf:taxonomyId>18160</wpf:taxonomyId>
<ytcp:youTubeAssetType>web</ytcp:youTubeAssetType>
<ytcp:youTubeSavedMatchRights>Monetize in all countries</ytcp:youTubeSavedMatchRights>
<ytcp:youTubeSavedUsageRights>Monetize in all countries</ytcp:youTubeSavedUsageRights>
</item>
</channel>
</rss>
here is my code
function parsexml($xml)
{
$xmlparse=simplexml_load_string($xml)
var_dump($xmlparse);
}
You won't get all nodes because they use namespaces, for exmple: pl:id. To parse these you could use Xpath. first example grabs all pl:added second one gets media:hash.
You can only use the following if you know the file will always use the same prefix. If not, you have to register the namespace for each simpleXMLElement object you use.
<?
$str = '*your string here*';
$xml = simplexml_load_string($str);
// to get pl:added
foreach($xml->xpath('//media:content') as $element) {
$added = $element->xpath('//pl:added');
}
//output $added
echo "<pre>";
var_dump($added);
// to get media:hash
foreach($xml->xpath('//media:thumbnail') as $element) {
$hash = $element->xpath('//media:hash');
}
//output $hash
echo "<pre>";
var_dump($hash);
?>
When you need to register namespaces you can do the following. First you can var dump the namespaces so you know which url you need to use.
["os"]=>string(36) "http://a9.com/-/spec/opensearch/1.1/" So for os you need that url.
<?
$str = '*your string here*';
$xml = simplexml_load_string($str);
// to get the namespaces uncomment the next 3 lines
// $namespaces = $xml->getNamespaces(true);
// echo "<pre>";
// var_dump($namespaces);
$xml->registerXPathNamespace('media', 'http://search.yahoo.com/mrss/');
foreach($xml->xpath('//media:content') as $element) {
$element->registerXPathNamespace('pl', 'http://xml.theplatform.com/data/object');
$added = $element->xpath('//pl:added');
}
echo "<pre>";
var_dump($added);
$xml->registerXPathNamespace('media', 'http://search.yahoo.com/mrss/');
foreach($xml->xpath('//media:thumbnail') as $element) {
$element->registerXPathNamespace('media', 'http://search.yahoo.com/mrss/');
$hash = $element->xpath('//media:hash');
}
echo "<pre>";
var_dump($hash);
?>
I want to load XML file and then remove all <Charge> where <DispositionDate> is bigger/older then 7 years. Date format is YYYY-MM-DD.
XML example:
<BackgroundReports userId="" password="" account="" >
<BackgroundReportPackage>
<Screenings>
<Screening type="criminal" qualifier="">
<CriminalReport>
<CriminalCase>
<AgencyReference type="Docket">
<IdValue>CR-0870120-09</IdValue>
</AgencyReference>
<Charge>
<ChargeId>
<IdValue>1</IdValue>
</ChargeId>
<ChargeOrComplaint>DUI: HIGHEST RTE OF ALC (BAC .16+) 1ST OFF</ChargeOrComplaint>
<ChargeTypeClassification>unknown</ChargeTypeClassification>
<DispositionDate>2009-04-07</DispositionDate>
</Charge>
<Charge>
<ChargeId>
<IdValue>2</IdValue>
</ChargeId>
<ChargeOrComplaint>CARELESS DRIVING</ChargeOrComplaint>
<ChargeTypeClassification>unknown</ChargeTypeClassification>
<DispositionDate>2010-08-02</DispositionDate>
</Charge>
<Charge>
<ChargeId>
<IdValue>3</IdValue>
</ChargeId>
<ChargeOrComplaint>STATUTE: 475 PC</ChargeOrComplaint>
<ChargeTypeClassification>misdemeanor</ChargeTypeClassification>
<OffenseDate>1988-11-05</OffenseDate>
<Disposition>CONVICTED</Disposition>
<DispositionDate>1988-11-09</DispositionDate>
<DispositionDate>1988-11-05</DispositionDate>
<DispositionDate>1988-11-09</DispositionDate>
</Charge>
</CriminalCase>
</CriminalReport>
</Screening>
</Screenings>
</BackgroundReportPackage>
</BackgroundReports>
I know how to open and close/save file using PHP, I don't know how to delete the part i don't want... If anyone would help me with that I would be extremly thankfull!
You can either use SimpleXML, DOM or XSL for it.
Example XML (shortened for brevity (from Revision 1 of your question)):
$xml = <<< XML
<CriminalCase>
<Charge>
<DispositionDate>1995-12-21</DispositionDate>
</Charge>
<Charge>
<DispositionDate>2010-12-21</DispositionDate>
</Charge>
</CriminalCase>
XML;
With SimpleXml
$sevenYearsAgo = new DateTime('-7 years');
$CriminalCase = new SimpleXmlElement($xml);
for ($i = 0; $i < $CriminalCase->Charge->count(); $i++) {
$dispositionDate = new DateTime($CriminalCase->Charge->DispositionDate);
if ($dispositionDate < $sevenYearsAgo) {
unset($CriminalCase->Charge[$i]);
}
}
echo $CriminalCase->asXml();
With DOM
$dom = new DOMDocument;
$dom->loadXml($xml);
$xpath = new DOMXPath($dom);
$oldCases = $xpath->query(
sprintf(
'//Charge[substring-before(DispositionDate, "-") < %d]',
date('Y', strtotime('-7 years'))
)
);
foreach ($oldCases as $oldCase) {
$oldCase->parentNode->removeChild($oldCase);
}
echo $dom->saveXml();
With XSLT
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:date="http://exslt.org/dates-and-times"
extension-element-prefixes="date">
<xsl:output indent="yes" method="xml"/>
<xsl:template match="/">
<CriminalCase>
<xsl:apply-templates />
</CriminalCase>
</xsl:template>
<xsl:template match="Charge">
<xsl:if test="date:year(DispositionDate) > date:year() - 7">
<xsl:copy-of select="."/>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
and then use this PHP Code to transform it
$doc = new DOMDocument();
$xsl = new XSLTProcessor();
$doc->loadXml($xsl);
$xsl->importStyleSheet($doc);
$doc->loadXml($xml);
echo $xsl->transformToXML($doc);
Here are some tips on how to get started:
You need to parse the XML to something a little easier to work with. PHP has a library called SimpleXML.
Loop through the data and remove the objects which are older than 7 years. To compare dates you have to first convert the dates you got from the XML to something PHP can process as a date. Take a look at strtotime which gives you the timestamp (seconds since 1970, actually 1901 for version > 5.1.0) or DateTime which supports dates before 1970.
To check if the fetched date is older than 7 years ago, you need to (one way) subtract the timestamp with the current timestamp, and see if that value is greater than 7 years in seconds. Or if you use DateTime, you can take a look at DateTime::diff. Remove the objects that you iterate over that are older than 7 years (unset).
To save as XML again, take a look at SimpleXMLElement::asXML
Hope that helps!