Accessing element contents and namespaced attributes with SimpleXML parser [duplicate] - php

This question already has answers here:
How to extract and access data from JSON with PHP?
(1 answer)
How do you parse and process HTML/XML in PHP?
(31 answers)
Closed 3 years ago.
We've got an XML file with this format:
<Quiz xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<id>0</id>
<title>Ganz Anderer Titel</title>
<questions>
<Question xsi:type="ChoiceQuestion">
<title>Frage1</title>
<id>0</id>
<rightAnswer>1</rightAnswer>
</Question>
<Question xsi:type="ChoiceQuestion">
<title>Frage2</title>
<id>1</id>
<rightAnswer>2</rightAnswer>
</Question>
<Question xsi:type="ChoiceQuestion">
<title>Frage2</title>
<id>2</id>
<rightAnswer>3</rightAnswer>
</Question>
</questions>
<expireDate>2018-06-06T00:00:00</expireDate>
</Quiz>
We now need to parse this XML file, but we are not able to access the content or attributes of the questions element.
We are using PHP 7 with the built in SimpleXML parser.
echo json_encode($xml->questions);
displays this
{"Question":[{"title":"Frage1","id":"0","rightAnswer":"1"},{"title":"Frage2","id":"1","rightAnswer":"2"},{"title":"Frage2","id":"2","rightAnswer":"3"}]}
but we have no idea how to get the data of each question individually.

As suggested in the comments, a simple foreach loop will let you loop through each item in the list. To get namespaced attributes, use the SimpleXMLElement::attributes() method:
$xml = <<< XML
<Quiz xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<id>0</id>
<title>Ganz Anderer Titel</title>
<questions>
<Question xsi:type="ChoiceQuestion">
<title>Frage1</title>
<id>0</id>
<rightAnswer>1</rightAnswer>
</Question>
<Question xsi:type="ChoiceQuestion">
<title>Frage2</title>
<id>1</id>
<rightAnswer>2</rightAnswer>
</Question>
<Question xsi:type="ChoiceQuestion">
<title>Frage2</title>
<id>2</id>
<rightAnswer>3</rightAnswer>
</Question>
</questions>
<expireDate>2018-06-06T00:00:00</expireDate>
</Quiz>
XML;
$x = new SimpleXMLElement($xml);
foreach ($x->questions->Question as $q) {
printf(
"Question %d:\nType:%s\nTitle:%s\nRight answer:%s\n",
$q->id,
$q->attributes("xsi", true)->type,
$q->title,
$q->rightAnswer
);
}

Related

PHP XML not parsing with SimpleXml [duplicate]

This question already has answers here:
Reference - How do I handle Namespaces (Tags and Attributes with a Colon in their Name) in SimpleXML?
(2 answers)
Closed 2 years ago.
my xml not parsing, i have no idea why
First line of xml not parsing, but second line parsing good
I know about im missings whatever in code, but searched in google and not find correct answer for it
// this xml not work, with <soap:Envelope> tags
$string = '<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<GetBrandsListResponse xmlns="http://tempuri.org/">
<GetBrandsListResult>
<DocumentElement>
<BrandLst>
<ID>1</ID>
<Name>Audi</Name>
</BrandLst>
<BrandLst>
<ID>350</ID>
<Name>BMW</Name>
</BrandLst>
</DocumentElement>
</GetBrandsListResult>
</GetBrandsListResponse>
</soap:Body>
</soap:Envelope>';
// but this xml works, without soap envelope tags
$string = '
<BrandLst>
<ID>1</ID>
<Name>Audi</Name>
</BrandLst>
';
$xml = simplexml_load_string($string);
var_dump($xml);
Fixed with adding xpath and registerXPathNamespace
$xml = simplexml_load_string($string);
$xml->registerXPathNamespace('default', 'http://tempuri.org/');
$auto = $xml->xpath("//default:BrandLst");

Reading Xml Nodes with PHP [duplicate]

This question already has answers here:
How do you parse and process HTML/XML in PHP?
(31 answers)
Closed 6 years ago.
I have a problem with PHP. I cannot read xml with PHP, and with SimpleXml.
How can I do.
My Xml files is below.
I just want your CompanyList.
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<soap:Header>
<wsa:Action>http://www.temp/Response</wsa:Action>
<wsa:MessageID>urn:uuid:eac190a5-c833-4dee-b4ef-fa81b0bad5c1</wsa:MessageID>
<wsa:RelatesTo>urn:uuid:834ace07-1e96-49d9-b958-3b2b87169917</wsa:RelatesTo>
<wsa:To>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</wsa:To>
<wsse:Security>
<wsu:Timestamp wsu:Id="Timestamp-55f3bafa-087a-4971-975d-a314957b4282">
<wsu:Created>2016-11-17T15:12:46Z</wsu:Created>
<wsu:Expires>2016-11-17T15:17:46Z</wsu:Expires>
</wsu:Timestamp>
</wsse:Security>
</soap:Header>
<soap:Body>
<ListResponse xmlns="http://fatura.edoksis.net">
<CompanyResult>
<Success>1</Sonuc>
<CompanyList>
<Company>
<Identifier>8380436088</Identifier>
<RegisterTime>2016-10-21T00:00:00Z</RegisterTime>
</Company>
<Company>
<Identifier>8380436088</Identifier>
<RegisterTime>2016-10-21T00:00:00Z</RegisterTime>
</Company>
</CompanyList>
</CompanyResult>
</CompanyResult>
</soap:Body>
</soap:Envelope>
$dom = new DOMDocument;
$dom->loadXML($response);
$books = $dom->getElementsByTagName('Identifier');
foreach ($books as $book) {
echo $book->nodeValue ."</br>";
}

How to get XML-Namespace-Attribute with SimpleXml? [duplicate]

This question already has an answer here:
Simplexml get attributes with a namespace
(1 answer)
Closed 8 years ago.
I try to use the Immobilienscout24-API to get Offerings of my Customer to his homepage.
I get an XML-Result with the form like here.
After parsing this result with
$obj = new SimpleXMLElement($myXmlString);
the attribute xsi:type of the element realEstateElement is lost. How can I access that element?
Thanks!
<?php
$xml = <<<XML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<realestates:realEstates xmlns:ns2="http://rest.immobilienscout24.de/schema/platform/gis/1.0" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:common="http://rest.immobilienscout24.de/schema/common/1.0" xmlns:realestates="http://rest.immobilienscout24.de/schema/offer/realestates/1.0">
<Paging>
<next xlink:href="http://rest.sandbox-immobilienscout24.de/restapi/api/offer/v1.0/user/me/realestate?pagenumber=2"/>
<pageNumber>1</pageNumber>
<pageSize>20</pageSize>
<numberOfPages>12</numberOfPages>
<numberOfHits>222</numberOfHits>
</Paging>
<realEstateList>
<realEstateElement xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:offerlistelement="http://rest.immobilienscout24.de/schema/offer/listelement/1.0" xsi:type="offerlistelement:OfferHouseRent" xlink:href="http://rest.sandbox-immobilienscout24.de/restapi/api/offer/v1.0/user/me/realestate/62283354" modification="2013-12-05T09:13:45.000+01:00" creation="2013-12-05T09:13:37.000+01:00" publishDate="2013-12-07T20:37:38.333+01:00" id="62283354">
<externalId>62283354</externalId>
<title>Unterbach Haus</title>
<address>
<street>Eichenwand</street>
<houseNumber>2</houseNumber>
<postcode>40627</postcode>
<city>Düsseldorf</city>
<geoHierarchy>
<continent>
<geoCodeId>1</geoCodeId>
<fullGeoCodeId>1</fullGeoCodeId>
</continent>
<country>
<geoCodeId>276</geoCodeId>
<fullGeoCodeId>1276</fullGeoCodeId>
</country>
<region>
<geoCodeId>10</geoCodeId>
<fullGeoCodeId>1276010</fullGeoCodeId>
</region>
<city>
<geoCodeId>12</geoCodeId>
<fullGeoCodeId>1276010012</fullGeoCodeId>
</city>
<quarter>
<geoCodeId>57</geoCodeId>
<fullGeoCodeId>1276010012057</fullGeoCodeId>
</quarter>
<neighbourhood>
<geoCodeId>5111000008401</geoCodeId>
</neighbourhood>
</geoHierarchy>
</address>
<realEstateState>ACTIVE</realEstateState>
<common:publishChannels>
<publishChannel id="10000" title="Immobilienscout24"/>
<publishChannel id="10001" title="Homepage"/>
</common:publishChannels>
<price>
<value>45444</value>
<currency>EUR</currency>
</price>
<livingSpace>440</livingSpace>
<plotArea>460</plotArea>
<numberOfRooms>5</numberOfRooms>
<builtInKitchen>false</builtInKitchen>
</realEstateElement>
</realEstateList>
</realestates:realEstates>
XML;
$sxml = new SimpleXMLElement($xml);
var_dump($sxml->realEstateList->realEstateElement->attributes('xsi', true)->type);
http://www.php.net/manual/en/simplexmlelement.attributes.php Comments might be useful ;)

PHP newbie- specific scenario on how to parse an XML value stored in a variable using SimpleXML [duplicate]

This question already has an answer here:
php simple xml parse problem on invalid tags
(1 answer)
Closed 9 years ago.
I want to parse an XML data stored in a variable, using Simple XML.
THis is the data I am talking about:
<SearchResults:searchresults xsi:schemaLocation="http://www.zillow.com/static/xsd/SearchResults.xsd /vstatic/ae1bf8a790b67ef2e902d2bc04046f02/static/xsd/SearchResults.xsd">
<request>
<address>2114 Bigelow Ave</address>
<citystatezip>Seattle, WA</citystatezip>
</request>
<message>
<text>Request successfully processed</text>
<code>0</code>
</message>
<response>
<results>
<result>
<zpid>48749425</zpid>
<links>
<homedetails>http://www.zillow.com/homedetails/2114-Bigelow-Ave-N-Seattle-WA-98109/48749425_zpid/</homedetails>
<graphsanddata>http://www.zillow.com/homedetails/charts/48749425_zpid,1year_chartDuration/?cbt=7522682882544325802%7E9%7EY2EzX18jtvYTCel5PgJtPY1pmDDLxGDZXzsfRy49lJvCnZ4bh7Fi9w**</graphsanddata>
<mapthishome>http://www.zillow.com/homes/map/48749425_zpid/</mapthishome>
<comparables>http://www.zillow.com/homes/comps/48749425_zpid/</comparables>
</links>
<address>
<street>2114 Bigelow Ave N</street>
<zipcode>98109</zipcode>
<city>Seattle</city>
<state>WA</state>
<latitude>47.63793</latitude>
<longitude>-122.347936</longitude>
</address>
<zestimate>
<amount currency="USD">1219500</amount>
<last-updated>11/03/2009</last-updated>
<oneWeekChange deprecated="true"/>
<valueChange duration="30" currency="USD">-41500</valueChange>
<valuationRange>
<low currency="USD">1024380</low>
<high currency="USD">1378035</high>
</valuationRange>
<percentile>0</percentile>
</zestimate>
<localRealEstate>
<region id="271856" type="neighborhood" name="East Queen Anne">
<zindexValue>525,397</zindexValue>
<zindexOneYearChange>-0.144</zindexOneYearChange>
<links>
<overview>http://www.zillow.com/local-info/WA-Seattle/East-Queen-Anne/r_271856/</overview>
<forSaleByOwner>http://www.zillow.com/homes/fsbo/East-Queen-Anne-Seattle-WA/</forSaleByOwner>
<forSale>http://www.zillow.com/east-queen-anne-seattle-wa/</forSale>
</links>
</region>
<region id="16037" type="city" name="Seattle">
<zindexValue>381,764</zindexValue>
<zindexOneYearChange>-0.074</zindexOneYearChange>
<links>
<overview>http://www.zillow.com/local-info/WA-Seattle/r_16037/</overview>
<forSaleByOwner>http://www.zillow.com/homes/fsbo/Seattle-WA/</forSaleByOwner>
<forSale>http://www.zillow.com/seattle-wa/</forSale>
</links>
</region>
<region id="59" type="state" name="Washington">
<zindexValue>263,278</zindexValue>
<zindexOneYearChange>-0.066</zindexOneYearChange>
<links>
<overview>http://www.zillow.com/local-info/WA-home-value/r_59/</overview>
<forSaleByOwner>http://www.zillow.com/homes/fsbo/WA/</forSaleByOwner>
<forSale>http://www.zillow.com/wa/</forSale>
</links>
</region>
</localRealEstate>
</result>
</results>
</response>
</SearchResults:searchresults>
Now the above type of XML is stored in variable named $zillow_data
First I load it using SimpleXML using the code
$xml = simplexml_load_string($zillow_data);
Now, I want to get the "message" value as shown in the XML data above.
When I try
foreach($xml->message[0]->text[0] as $response)
It does not work.
When I try something like the below code I get an error in Netbeans IDE
foreach($xml->SearchResults:searchresults[0]->message[0]->text[0] as $response)
The error I get is "unexpected : "
How do I correctly fetch the message in above XML data?
Also how do I parse through all the "result" elements, one by one?
If You use the code:
$xml = simplexml_load_string($string);
while the $string variable contains the XML, the first element <SearchResults:searchresults> becomes the main $xml SimpleXMLElement object, while the child tags <request>, <message> and <response> are its properties.
Thus, forgetting about the undefined namespace warnings, You should be able to do e.g.:
foreach($xml->response->results->result as $result) {
echo (string) $result->zpid;
}
There is only one message with only one text element, thus if You want to echo this one, You should only do:
echo (string) $xml->message->text;
Do a var_dump($xml); to understand the XML structure being transformed into objects and arrays after loading it with SimpleXML.

display only nodes in XML with specific attributes in php [duplicate]

This question already has answers here:
Using XPath, How do I select a node based on its text content and value of an attribute?
(2 answers)
Closed 9 years ago.
if i have:
<listing>
<name>Bob</name>
<age>20</age>
<hair>red</hair>
</listing>
<listing>
<name>John</name>
<age>24</age>
<hair>black</hair>
</listing>
how do i code my php page to only display listings if hair = black
so that it would only pull in
<listing>
<name>John</name>
<age>24</age>
<hair>black</hair>
</listing>
Thanks
Use XPath.
// First, your XML must be wraped with some root tag.
$data = <<<XML
<root>
<listing>
<name>Bob</name>
<age>20</age>
<hair>red</hair>
</listing>
<listing>
<name>John</name>
<age>24</age>
<hair>black</hair>
</listing>
</root>
XML;
// Instancing the SimpleXMLElement within the XML(obviously)
$xml = new SimpleXMLElement($data);
// XPath
$xpath = $xml->xpath("listing[contains(hair,'black')]");
/**
* eXplained XPath:
* <listing> that
* <hair>'s content is equal black
*/
foreach($xpath as $node){
// just for fun echoes the <results> node
echo $node->asXml();
}

Categories