simplexml 'Trying to get property of non-object in' error - php

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

Related

How to make foreach work with this PHP script - GET API

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

Parsing a JSON string with multiple arrays

I am trying to parse this JSON string
$json = {"fields":{
"relationshipStatus":[{"fieldId":4,"name":"Committed"},{"fieldId":2,"name":"Dating"},{"fieldId":6,"name":"Engaged"},{"fieldId":3,"name":"Exclusive"},{"fieldId":7,"name":"Married"},{"fieldId":8,"name":"Open Relationship"},{"fieldId":5,"name":"Partnered"},{"fieldId":1,"name":"Single"}],
"ethnicity":[{"fieldId":1,"name":"Asian"},{"fieldId":2,"name":"Black"},{"fieldId":3,"name":"Latino"},{"fieldId":4,"name":"Middle Eastern"},{"fieldId":5,"name":"Mixed"},{"fieldId":6,"name":"Native American"},{"fieldId":8,"name":"Other"},{"fieldId":9,"name":"South Asian"},{"fieldId":7,"name":"White"}],
}}
Using this foreach loop, ultimately I want to be able to take the data and use them as Select / List dropdowns on a form.
foreach($json['fields'] as $item){
foreach($item['relationshipStatus'] as $relationship){
echo $relationship['name'] . " " . $relationship['fieldId'] . "<br/>";
}
foreach($item['ethnicity'] as $ethnicity){
echo $ethnicity['name'] . " " . $ethnicity['fieldId'] . "<br/>";
}
}
No matter how I try to pull the data out, I keep getting errors similar to:
Notice: Undefined index: relationshipStatus in
/Applications/MAMP/htdocs/updateprofile.php on line 126 Warning:
Invalid argument supplied for foreach() in
/Applications/MAMP/htdocs/updateprofile.php on line 126
What am I doing wrong?
The first foreach selects already relationshipStatus and ethnicity. Maybe the following changes show what I mean:
foreach($json['fields'] as $key=>$item){
if ($key == 'relationshipStatus')
foreach($item as $relationship){
echo $relationship['name'] . " " . $relationship['fieldId'] . "<br/>";
}
else if ($key == 'ethnicity')
foreach($item as $ethnicity){
echo $ethnicity['name'] . " " . $ethnicity['fieldId'] . "<br/>";
}
}
Here, you iterating the JSON Object in a wrong way.The array values you want to fetch is actually under $json['fields']['relationshipStatus'].
var name = $json['fields']['relationshipStatus']['name'];
var fieldId = $json['fields']['relationshipStatus']['fieldId'];
=============================== OR ========================================
As described by the A.fink
foreach($json['fields'] as $key=>$item){
if ($key == 'relationshipStatus')
foreach($item as $relationship){
echo $relationship['name'] . " " . $relationship['fieldId'] . "<br/>";
}
else if ($key == 'ethnicity')
foreach($item as $ethnicity){
echo $ethnicity['name'] . " " . $ethnicity['fieldId'] . "<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
}

Pulling data from Google Cal xml

I'm running into an error when trying to pull some data from Google Cal using PHP. Here is the code:
$url = $_POST['url'];
$xml = file_get_contents($url);
$feed = simplexml_load_string($xml);
$ns= $feed->getNameSpaces(true);
foreach ($feed->entry as $entry) {
$eventdetail = $entry->children($ns["gd"]);
$when_atr = $eventdetail->when[0]->attributes();
$title = $entry->title;
echo "<div class='eventTitle'>".$title . "</div>";
$where = $eventdetail->where[0]->attributes();
echo "<div class='eventLocation'>" . $where . "</div>" . '<br />';
$start = new DateTime($when_atr['startTime']);
echo "<div class='eventTime'>".$start->format('D F jS, g:ia') . " to ";
$end = new DateTime($when_atr['endTime']);
echo $end->format('g:ia')."</div>" . '<br />' ;
}
The titles work just fine, but for both the "when" and "where" I'm running into problems with the code when[0]->attributes(); and where[0]->attributes();.
The error I get is
Fatal error: Call to a member function attributes() on a non-object
What can I do to prevent this from happening?

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