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);
Related
$xml = '<?xml version="1.0" encoding="UTF-8"?>
<stw:ThumbnailResponse xmlns:stw="http://www.shrinktheweb.com/doc/stwresponse.xsd">
<stw:Response>
<stw:ThumbnailResult>
<stw:Thumbnail Exists="true">http://imagelink.com</stw:Thumbnail>
<stw:Thumbnail Verified="false">delivered</stw:Thumbnail>
</stw:ThumbnailResult>
<stw:ResponseStatus>
<stw:StatusCode>refresh</stw:StatusCode>
</stw:ResponseStatus>
<stw:ResponseTimestamp>
<stw:StatusCode>1413812009</stw:StatusCode>
</stw:ResponseTimestamp>
<stw:ResponseCode>
<stw:StatusCode>HTTP:200</stw:StatusCode>
</stw:ResponseCode>
<stw:CategoryCode>
<stw:StatusCode></stw:StatusCode>
</stw:CategoryCode>
<stw:Quota_Remaining>
<stw:StatusCode>132</stw:StatusCode>
</stw:Quota_Remaining>
<stw:Bandwidth_Remaining>
<stw:StatusCode>999791</stw:StatusCode>
</stw:Bandwidth_Remaining>
</stw:Response>
</stw:ThumbnailResponse>';
$dom = new DOMDocument;
$dom->loadXML($xml);
$result = $dom->getElementsByTagName('stw:Thumbnail')->item(0)->nodeValue;
$status = $dom->getElementsByTagName('stw:Thumbnail')->item(0)->nodeValue;
echo $result;
Having the above code should output http://imagelink.com and $status should hold "delivered" - but none of these work instead I am left with the error notice that:
Trying to get property of non-object
I have tried different xml parsing alternatives like simplexml (but that did not work when the tag names have : in it ) and i tried looping through the each scope in the xml (ThumbNailresponse, response and then thumbnailresult) without luck.
How can i get the values inside stw:Thumbnail?
You need to specify a namespace and the method DOMDocument::getElementsByTagName can't handle it. In the manual:
The local name (without namespace) of the tag to match on.
You can use DOMDocument::getElementsByTagNameNS instead:
$dom = new DOMDocument;
$dom->loadXML($xml);
$namespaceURI = 'http://www.shrinktheweb.com/doc/stwresponse.xsd';
$result = $dom->getElementsByTagNameNS($namespaceURI, 'Thumbnail')->item(0)->nodeValue;
Using simple xml you could use ->children() method on this one:
$xml = simplexml_load_string($xml_string);
$stw = $xml->children('stw', 'http://www.shrinktheweb.com/doc/stwresponse.xsd');
echo '<pre>';
foreach($stw as $e) {
print_r($e);
// do what you have to do here
}
This code actually runs just fine for me ---
Typically, that sort of error means you may've made a typo on your $dom object - double check it and try again.
Also, it is notable that you'll want to change the item(0) to item(1) when you're setting your $status variable.
$result = $dom->getElementsByTagName('stw:Thumbnail')->item(0)->nodeValue;
$status = $dom->getElementsByTagName('stw:Thumbnail')->item(0)->nodeValue;
I'm trying to parse an xml data that I'm getting via an api call. I can use file_get_contents to read into a string but simpleXML_load_string seems to fail to read it. I can save it to a file and then simpleXML_load_file works. But I would rather not write the contents to a file. I can't seem to understand how to use DOM or XMLParse with this either. I'm new to PHP and parsing XML. The output data from the api call is below.
<Search>
<DS_Rating>DS3</DS_Rating>
<Overall>17.5</Overall>
<LargestGiftLow>0</LargestGiftLow>
<LargestGiftHigh>0</LargestGiftHigh>
<EstimatedCapacityRange>I - $15,000 - $24,999</EstimatedCapacityRange>
<EstimatedCapacity>20452</EstimatedCapacity>
<RealEstateEst>270073</RealEstateEst>
<RealEstateCount>1</RealEstateCount>
<LikelyMatchesCount>0</LikelyMatchesCount>
<LikelyMatchesTotal>0</LikelyMatchesTotal>
<FndBoard></FndBoard>
<GSBoard></GSBoard>
<PoliticalLikelyCount>0</PoliticalLikelyCount>
<PoliticalLikelyTotal>0</PoliticalLikelyTotal>
<BusinessRevenues>0</BusinessRevenues>
<SECStockValue>0</SECStockValue>
<SECInsider></SECInsider>
<MarketGuide></MarketGuide>
<IRS990PF></IRS990PF>
<RealEstateTrust></RealEstateTrust>
<MarketGuideComp>0</MarketGuideComp>
<MarketGuideOptions>0</MarketGuideOptions>
<BusinessAffiliation></BusinessAffiliation>
<Pension></Pension>
<PensionAssets>0</PensionAssets>
<CorpTech></CorpTech>
<Pilot></Pilot>
<AirplaneOwner></AirplaneOwner>
<Boat></Boat>
<submit_time>2014-03-11 15:48:45</submit_time>
</Search>
Figured out that the issue was that what I was seeing in the browser was actually a php output with html_entiity encoded. I was able to process it with the code below which let me load it with simplexml.
$rawxml = html_entity_decode($rawxml);
$rawxml = str_replace(array(' ', "<pre>"), '', $rawxml);
$rawxml = utf8_encode($rawxml);
$xml = simplexml_load_string($rawxml);
If you XML is in a file use
simplexml_load_file
if you have it in a string use
simplexml_load_string
Then you can use the following code to access it.
<?php
$yourxml = simplexml_load_file('your.xml');
echo $yourxml->search[0]->DS_Rating;
?>
This would then output
DS3
to the browser via the 'echo' in your code. I hope this points you in the correct direction.
Try to use this:
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="utf-8" ?>'.$yourXMLString);
In DOM you load the XML into a DOMDocument and create a DOMXpath instance for it.
$dom = new DOMDocument();
$dom->loadXml($xmlString);
//$dom->load($xmlFile);
$xpath = new DOMXpath($dom);
DOMXpath::evaluate() is used to fetch data from the DOM.
$rating = $dom->evaluate('string(/Search/DS_Rating)');
An Xpath expression like /Search/DS_rating always returns a node list. You can use foreach() to iterate it. The string() function in Xpath takes the first node from the list and casts it into a string. If here is not node in the list the result is an empty string.
$xmlString = <<<'XML'
<Search>
<DS_Rating>DS3</DS_Rating>
<Overall>17.5</Overall>
</Search>
XML;
$dom = new DOMDocument();
$dom->loadXml($xmlString);
$xpath = new DOMXpath($dom);
var_dump(
$xpath ->evaluate('string(/Search/DS_Rating)')
);
Output: https://eval.in/118921
string(3) "DS3"
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));
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());
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;