Reteras Remus
Reteras Remus

Reputation: 933

XML PHP parsing

I have the following temp.XML document:

<?xml version="1.0" encoding="UTF-8"?>
<services_api_response version="2.0">
  <status>
    <code>0</code>
    <message>OK</message>
  </status>
  <service id="82dadd66a5048cc85ed0b8da1d835f2a">
    <countries>
      <country code="BA" vat="17.00" approved="true" name="Bosnia and Herzegovina">
        <prices>
          <price vat_included="false" currency="BAM" all_operators="true" amount="2.00">
            <message_profile shortcode="091810700" all_operators="true" keyword="TXT ABC">
              <operator code="BH Mobile" billing_type="MO" revenue="0.84" default_billing_status="OK" name="BH Mobile"/>
              <operator code="HT-ERONET" billing_type="MO" revenue="0.84" default_billing_status="OK" name="HT-ERONET"/>
              <operator code="M:tel" billing_type="MT" revenue="0.84" default_billing_status="Failed" name="M:tel"/>
            </message_profile>
          </price>
        </prices>
        <promotional_text>
          <local>Cena: 2,00 BAM + PDV
Podr&#353;ka: 000000000| [email protected] Mobilna Naplata: fortumo.com</local>
          <english>Price: 2.00 BAM + VAT
Support: 000000000| [email protected]
Mobile Payment by fortumo.com</english>
        </promotional_text>
      </country>
     </countries>
    </service>
</services_api_response>

and the PHP File:

$obj = simplexml_load_file('temp.xml');

echo '---> '.$obj -> countries[0] -> promotional_text[0] -> local[0];

But I get nothing.

Upvotes: 0

Views: 238

Answers (4)

felipsmartins
felipsmartins

Reputation: 13549

You could use xpath, like this:

<?php
$xml = simplexml_load_file('/tmp/temp.xml');
$local = $xml->xpath('//countries/country/promotional_text/local');

print_r($local[0]);

Upvotes: 0

MrCode
MrCode

Reputation: 64526

echo (string) $obj->service[0]->countries[0]->country[0]->promotional_text[0]->local[0];

Outputs

Cena: 2,00 BAM + PDV

Podrška: 000000000| [email protected] Mobilna Naplata: fortumo.com

Codepad demo here

Keep in mind it's good practice to cast to a string when echoing a SimpleXML value because you are targeting an object.

Upvotes: 2

Samuel Cook
Samuel Cook

Reputation: 16828

You forgot a couple of nodes:

echo '---> '.$obj -> service[0] -> countries[0] -> country[0] -> promotional_text[0] -> local[0];

Upvotes: 2

Decent Dabbler
Decent Dabbler

Reputation: 22783

try:

echo '---> ' . $obj->service[0]
                   ->countries[0]
                   ->country[0]
                   ->promotional_text[0]
                   ->local[0];

Upvotes: 2

Related Questions