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
}
Related
I'm working on a script that will retrieve API information of the 'near earth objects' from NASA's website. User selects date, api grabs the information and displays it. How do I fix the foreach in this script? would appreciate some help with this.
$jsonAsteroids = file_get_contents("https://api.nasa.gov/neo/rest/v1/feed?start_date=2018-08-01&end_date=2018-08-04&api_key=NNKOjkoul8n1CH18TWA9gwngW1s1SmjESPjNoUFo");
$data = json_decode($jsonAsteroids, true);
echo "<h4>Retrieving the first element (i.e. \"links\") of the JSON structure</h4>";
var_dump( $data["links"]);
echo "<h4>Retrieving the first element (i.e. \"next\") inside the \"links\" element</h4>";
echo( $data["links"]["next"]);
You were very close. Your main issue was that you used json_decode(..., true); which gives you an array, but then used the object->property syntax instead of object['property']. My suggestion is to use json_decode without the 2nd argument in this case.
Finally, your 2nd foreach was malformed.
<?php
$result = file_get_contents("https://api.nasa.gov/neo/rest/v1/feed?start_date=2018-08-01&end_date=2018-08-04&api_key=NNKOjkoul8n1CH18TWA9gwngW1s1SmjESPjNoUFo");
$data = json_decode($result);
foreach ($data->near_earth_objects as $date => $objects) {
echo "<p>" . count($objects) . " objects detected on $date</p>";
echo "<ol>";
foreach ($objects as $object) {
echo "<li>" . $object->name . " <a href='" . $object->nasa_jpl_url . "'>" . $object->nasa_jpl_url . "</a><br>";
echo "Diameter of the object: " . $object->estimated_diameter->meters->estimated_diameter_min . "-" . $object->estimated_diameter->meters->estimated_diameter_max . " metres<br>";
echo "<ul>";
foreach ($object->close_approach_data as $close_approach) {
echo "<li>Close approach: " . $close_approach->close_approach_date . " traveling at a velocity of " . $close_approach->relative_velocity->kilometers_per_hour . " km/h " . "missing " . $close_approach->orbiting_body . " by " . $close_approach->miss_distance->kilometers . " km</li> ";
}
echo "</ul>";
}
echo "</ol>";
}
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>";
}
I am trying to pass a PHP variable from a link created in a for each loop.
Here is the code on the page that generates the link and variable to send:
$xmlDoc = simplexml_load_file("products.xml");
$storeArray = array();
foreach($xmlDoc->product as $Product) {
echo "Name: " . $Product->name . ", ";
echo "Price: " . $Product->price . ", ";
$store = (string)$Product->store;
if (!array_key_exists($store, $storeArray)) {
$storeArray[$store] = "<a href='searchResults.php?storeSearch=<?php echo $store; ?>'>" .
$store . "</a>";
}}
foreach ($storeArray as $store) {
echo $store . "<br>";
}
Here is the code on the page that receives the variable:
$searchByStore = $_GET["storeSearch"];
echo "Store search variable is: " . $searchByStore;
The searchByStore variable is not being echoed. Any advice?
Here is how this url appears in the browser:
.../searchResults.php?storeSearch=%3C?php%20echo%20Best%20Buy;%20?%3E
Instead of the normal way, which is:
.../searchResults.php?storeSearch=Best%20Buy
And here is the XML file:
<product type="Electronics">
<name> Desktop</name>
<price>499.99</price>
<store>Best Buy</store>
</product>
<product type="Electronics">
<name>Lap top</name>
<price>599.99</price>
<store>Best Buy</store>
</product>
<product type="Hardware">
<name>Hand Saw</name>
<price>99.99</price>
<store>Lowes</store>
</product>
</products>
this is wrong:
$storeArray[$store] = "<a href='searchResults.php?storeSearch=<?php echo $store; ?>'>" .
$store . "</a>
";
change it to
$storeArray[$store] = "<a href='searchResults.php?storeSearch=".$store."'>".$store."</a>";
You cannot embed PHP code inside PHP code:
$storeArray[$store] = "<a href='searchResults.php?storeSearch=<?php echo $store; ?>'>" .
^^^^^^^^^^^^^^^^^^^^^
It should be
$storeArray[$store] = "<a blah blah storeSearch=" . $store . ">";
or
$storeArray[$store] = "<a blah blah storeSearch={$store}>";
I'm trying to parse the XML of http://www.mpgh.net/forum/external.php?type=RSS2&forumids=175
but I get this error, can't find whats wrong.
Notice: Trying to get property of non-object in C:\xampp\htdocs\crossfire\index.php on line 9
<?php
$rss = simplexml_load_file('http://www.mpgh.net/forum/external.php?type=RSS2&forumids=175');
for($i=0;$i<10;$i+=1) {
$namespaces = $rss->getNameSpaces(true);
$dc = $rss->children($namespaces['dc']);
echo "Title: " . $rss->channel->item[$i]->title . "<br>";
echo "Creator: " . $dc->channel->item[$i]->creator . "<br>";
echo "Link: " . $rss->channel->item[$i]->link . "<br><br>";
}
And my second question.
Why is this code only working properly at http://www.mpgh.net/forum/external.php?type=RSS2&forumids=175 and not at other pages like http://www.mpgh.net/forum/external.php?type=RSS2&forumids=168
Notice: Trying to get property of non-object in C:\xampp\htdocs\crossfire\index.php on line 7
<?php
$rss = New DOMDocument();
$rss = simplexml_load_file('http://www.mpgh.net/forum/external.php?type=RSS2&forumids=168');
for($i=0;$i<10;$i+=1) {
if (substr($rss->channel->item[$i]->title, 0, 9) == '[Release]') {
echo "Title: " . $rss->channel->item[$i]->title . "<br>";
echo "Link: " . $rss->channel->item[$i]->link . "<br><br>";
} else {
echo 'Hoi<br><br>';
}
}
Thanks.
I think the problem is that $ith index of $rss->channel->item is not set or not an object.
Try this; it will expose the problem:
$rss = simplexml_load_file('http://www.mpgh.net/forum/external.php?type=RSS2&forumids=175');
if ($rss===null || !is_object($rss))
die('Failed to load xml file.');
if (!is_object($rss->channel))
die('Channel is not an object!');
foreach ($rss->channel->item as $item)
if (is_object($item)) {
$namespaces = $rss->getNameSpaces(true);
$dc = $rss->children($namespaces['dc']);
echo "Title: " . $item->title . "<br>";
echo "Creator: " . $item->creator . "<br>";
echo "Link: " . $item->link . "<br><br>";
}
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;
}