parse xml file in php - php

How to parse this type of files in php
I have tried using
<?php
$xml ="office.xml";
// get first book title
$title=$xml->featureMember->AA_OFFICE;
// show title
echo $title;
echo '<br/>';
?>
if iam using gml:featuremember instead of featuremember i am getting an error in syntax
if i use featuremember iam getting ) Notice: Trying to get property of non-object
<gml:boundedBy>
<gml:null>unknown</gml:null>
</gml:boundedBy>
<gml:featureMember>
<kgp:AA_OFFICE fid="AA_OFFICE.1">
<kgp:the_geom>
<gml:Point srsName="http://www.opengis.net/gml/srs/epsg.xml#32645">
<gml:coordinates xmlns:gml="http://www.opengis.net/gml" decimal="." cs="," ts=" ">643630.3815,2498825.0741</gml:coordinates>
</gml:Point>
</kgp:the_geom>
<kgp:Name>MANMARK EXPORT PVT LTD</kgp:Name>
<kgp:Type/>
<kgp:Plot_No>55</kgp:Plot_No>
<kgp:Block_Name>AA</kgp:Block_Name>
</kgp:AA_OFFICE>
</gml:featureMember>

You are trying to use a string as an object. You have to create some form of XML Parsing object first. For example,
$xmlDoc = new DOMDocument();
$xmlDoc->load("office.xml");
More information
or
$xml = simplexml_load_file("office.xml");
More information

try to debug your xml
libxml_use_internal_errors(true);
$xml = simplexml_load_file("office.xml");
var_dump(libxml_get_errors());

Related

Trying to get property of non-object -> xml

I'm retrieving an xml:
$xml = file_get_contents($query);
echo $xml->Email;
echo $xml[0]->Email;
The xml (echo $xml) looks like this:
<GetUserInfo>
<Customer>TestUser</Customer>
<Email>test#test.com</Balance>
</GetUserInfo>
But both those approaches give the following error:
Notice: Trying to get property of non-object in test.php on line 86
Notice: Trying to get property of non-object in test.php on line 87
How can I get the value of Email and Customer?
file_get_contents() returns the file content, not an object. You can only use preg_match if you want to stick to string content (totally not advised):
preg_match('~<Email>([^<]+)</Email>~i', file_get_contents($__filePath__), $emails);
I recommend using DOMDocument and DOMXPath (code not tested):
$XMLDoc = new DOMDocument();
$XMLDoc->load($__filePath__);
$XPath = new DOMXPath($XMLDoc);
$emails = $XPath->query('//email');
foreach ($emails as $email)
var_dump($email->nodeValue);
You might use another Xpath expression like //email[1] or /GetUserInfo/Email
The foreach may also be replaced by $email = reset($emails); if you only want the first mail.
Your $xml is a string. $xml-> accesses a property of an object. That is not compatible. A php string is not an object.
You may want to use var_dump() instead of echo() to see all the details of your variables.
A simple string to object convertor is simplexml_load_string()
$xml='
<GetUserInfo>
<Customer>TestUser</Customer>
<Email>test#test.com</Email>
</GetUserInfo>
';
var_dump($xml);
$Xml = simplexml_load_string($xml);
var_dump($Xml);
echo($Xml->Email);

Parsing XML data from URL variable in PHP and WordPress

I have a PHP page that a service sends out a notice when a donation is made. My PHP page is supposed to grab the XML contents and parse it out for processing.
The service sends the following format:
http://myserver.com/myphp.com?details= xml data
I have the following code listening for this post:
//Load xml from post
$data = file_get_contents('php://input');
$xmlData = simplexml_load_string($data);
//grab mobile number to query mgive for user info
$mnumb= $xmlData->MobileNumber;
$mnumb=ltrim($mnumb,'1');
I am getting the following error when the service sends out the notice.
Warning: simplexml_load_string() [function.simplexml-load-string]: Entity: line 1: parser error : Start tag expected, '<' not found in
what am I missing or coding wrong?
12-18-2013 855cst
Thanks ThW.. Progress is being made.
I used your suggestion #2 to get the data.
When I do a print_r(xmlData), I get no output on the screen. However, when using chrome developer tool, I get the following output:
data=%3C%3Fxml+version%3D%221.0%22+encoding%3D%22utf-8%22%3F%3E%3CGetDonationStatusResult+xmlns%3Axsi%3D%22http%3A%2F%2Fwww.w3.org%2F2001%2FXMLSchema-instance%22+xmlns%3Axsd%3D%22http%3A%2F%2Fwww.w3.org%2F2001%2FXMLSchema%22%3E%3CResultCode+%3E0%3C%2FResultCode%3E%3CResultText+%2F%3E%3CRecordID+%3E0%3C%2FRecordID%3E%3CMobileNumber+%3E12142911111%3C%2FMobileNumber%3E%3CCarrierID+%3E31002%3C%2FCarrierID%3E%3CCarrierName+%3EAT%26amp%3BT+Wireless%3C%2FCarrierName%3E%3CDonationStatus+%3EUserAccepted%3C%2FDonationStatus%3E%3CMobileTransactionID+%3E62622731%3C%2FMobileTransactionID%3E%3CDonationMsgGUID+%3E9c17d57f-b54e-488a-8cf5-1c658d1aa618%3C%2FDonationMsgGUID%3E%3CCampaignID+%3E20409%3C%2FCampaignID%3E%3CShortCode+%3E27722%3C%2FShortCode%3E%3CMsgTime+%3E2013-12-17T12%3A53%3A18%3C%2FMsgTime%3E%3CMessageText+%3ELIBERIA+WAP%3C%2FMessageText%3E%3C%2FGetDonationStatusResult%3E&*
You can see MobileNumber is sent. But, when I echo $mnumb, I get no output. Am I missing something in my use of simplexml_load_string($data); to grab the MobileNumber?
It is not clear where you get the xml data from.
Read from the detail parameter in the url $xml = $_GET['detail'];
Read from the data parameter in the url $xml = $_GET['data'];
Read from the data parameter in the request body (post) $xml = $_POST['data'];
Read the raw post data $xml = file_get_contents("php://input");
Try to var_dump() the data:
var_dump($_GET, $_POST);
After you got the XML into a variable use DOM + Xpath to extract values from it:
$xml = <<<'XML'
<?xml version="1.0" encoding="utf-8"?>
<GetDonationStatusResult xmlns:xsi="w3.org/2001/XMLSchema-instance" xmlns:xsd="w3.org/2001/XMLSchema">
<ResultCode >0</ResultCode>
<ResultText />
<RecordID >0</RecordID>
<MobileNumber >19191112222</MobileNumber>
<CarrierID >31002</CarrierID>
<CarrierName >AT&T Wireless</CarrierName>
<DonationStatus >UserAccepted</DonationStatus>
<MsgTime >2013-12-17T20:53:05</MsgTime>
<MessageText >LIBERIA WAP</MessageText>
</GetDonationStatusResult>
XML;
$dom = new DOMDocument();
// try to load the xml
if ($dom->loadXml($xml)) {
$xpath = new DOMXpath($dom);
// read the first MobileNumber element as string
var_dump(
$xpath->evaluate('string(//MobileNumber)')
);
}
Output:
string(11) "19191112222"
Live Result

output only a specific node PHP XML

Im trying to save a specific node instead of the full xml file, but I get error.
Catchable fatal error: Argument 1 passed to DOMDocument::saveXML() must be an instance of DOMNode, instance of DOMNodeList given in php\corrdination.php on line 31
I'm following the doom documentation but since I don't create new element and only read from an already created xml file, it wont work with creating new elements.
My line 31 is
$resultX = $xpath->query('/stickers/sticker[id="200"]/position/x');
And when im trying to save only the changed node i write.
echo $xml->saveXML($resultX);
Any suggestion on how to do it ?
This is my whole php file.
$xml = new DOMDocument();
$xml->formatOutput = TRUE;
$xml->preserveWhiteSpace = FALSE;
$xml->load('../stickers.xml');
$xpath = new DOMXPath($xml);
$resultX = $xpath->query('/stickers/sticker[id="200"]/position/x');
$resultX->item(0)->nodeValue = "150";
echo $xml->saveXML($resultX);
If I only echo $xml->saveXML();
The query works but as I said, it saves the whole node structure.
XML file:
<stickers>
<sticker>
<position>
<x>0</x>
</position>
<text>Hello world </text>
<id>200</id>
</sticker>
</stickers>
Thanks
The error says you have to pass DOMNode to DOMDocument::saveXML(). So you need to change this line:
echo $xml->saveXML($resultX);
to this:
echo $xml->saveXML($resultX->item(0));

Simplexml not displaying info

I have made a search html page using IMDBAPI to create an xml file for that item I search. Then I have a php file that will parse through that file and only pull the data I want from the xml file to display. Everything seems to be working as I am getting a blank white page. The issue is that nothing is displaying.
Part of the XML
<IMDBDocumentList>
<item>
<rating>8.7</rating>
<rating_count>10301</rating_count>
<year>1999</year>
<genres>
<item>Animation</item>
<item>Action</item>
<item>Adventure</item>
<item>Comedy</item>
<item>Drama</item>
<item>Fantasy</item>
<item>Romance</item>
</genres>
<rated>PG</rated>
<title>Wan pîsu: One Piece</title>
<imdb_url>http://www.imdb.com/title/tt0388629/</imdb_url>
<directors>
<item>Kônosuke Uda</item>
</directors>
<actors>
<item>Mayumi Tanaka</item>
<item>Kazuya Nakai</item>
<item>Akemi Okamura</item>
<item>Kappei Yamaguchi</item>
<item>Mahito Ôba</item>
<item>Hiroaki Hirata</item>
<item>Colleen Clinkenbeard</item>
<item>Ikue Ôtani</item>
<item>Chikao Ôtsuka</item>
<item>Yuriko Yamaguchi</item>
<item>Luci Christian</item>
<item>Christopher Sabat</item>
<item>Sonny Strait</item>
<item>Kazuki Yao</item>
</actors>
PHP Parse
$lib = simplexml_load_file("test.xml");
$xml = $lib->IMDBDocumentList->item;
$rating = $xml->rating;
$year = $xml->year;
print $rating;
print $year;
IMDBDocumentList is your root node, so you don't need to address it:
$xml = $lib->item;

PHP DOMDocument getting Attribute of Tag

Hello I have an api response in xml format with a series of items such as this:
<item>
<title>blah balh</title>
<pubDate>Tue, 20 Oct 2009 </pubDate>
<media:file date="today" data="example text string"/>
</item>
I want to use DOMDocument to get the attribute "data" from the tag "media:file". My attempt below doesn't work:
$xmldoc = new DOMDocument();
$xmldoc->load('api response address');
foreach ($xmldoc->getElementsByTagName('item') as $feeditem) {
$nodes = $feeditem->getElementsByTagName('media:file');
$linkthumb = $nodes->item(0)->getAttribute('data');
}
What am I doing wrong? Please help.
EDIT: I can't leave comments for some reason Mark. I get the error
Call to a member function getAttribute() on a non-object
when I run my code. I have also tried
$nodes = $feeditem->getElementsByTagNameNS('uri','file');
$linkthumb = $nodes->item(0)->getAttribute('data');
where uri is the uri relating to the media name space(NS) but again the same problem.
Note that the media element is of the form not I think this is part of the problem, as I generally have no issue parsing for attibutes.
The example you provided should not generate an error. I tested it and $linkthumb contained the string "example text string" as expected
Ensure the media namespace is defined in the returned XML otherwise DOMDocument will error out.
If you are getting a specific error, please edit your post to include it
Edit:
Try the following code:
$xmldoc = new DOMDocument();
$xmldoc->load('api response address');
foreach ($xmldoc->getElementsByTagName('item') as $feeditem) {
$nodes = $feeditem->getElementsByTagName('file');
$linkthumb = $nodes->item(0)->getAttribute('data');
echo $linkthumb;
}
You may also want to look at SimpleXML and Xpath as it makes reading XML much easier than DOMDocument.
Alternatively,
$DOMNode -> attributes -> getNamedItem( 'MyAttribute' ) -> value;

Categories