0

here is my xml file note.xml file

<?xml version="1.0" encoding="ISO-8859-1"?>
<agents>
    <agent>
    <id>1</id>
    <image> img/primary-nav-logo.png</image>
    <name>Tommy Jenkin</name>
    <company>CJenkins Insurance</company>
    <street>Insurance150 S State Stree</street>
    <city>Linkend</city>
    <phone>(773) 561-4331</phone>
    </agent>
    <agent>
    <id>2</id>
    <image> img/primary-nav-logo.png</image>
    <name>Tommy Jenkin</name>
    <company>CJenkins Insurance</company>
    <street>Insurance150 S State Stree</street>
    <city>Linkend</city>
    <phone>(773) 561-4331</phone>
    </agent>
</agents>

and i have to print xml record of id 1 and i have write code in php like this

<?php
    $xml = simplexml_load_file("note.xml") or die("Error: Cannot create object");
    foreach($xml->xpath('//agent') as $item) { 
    $row = simplexml_load_string($item->asXML());
    $v = $row->xpath('//id[. ="1"]');
    if($v[0]){ 
        print $item->id; 
        print $item->image; 
        print $item->name; 
        print $item->company; 
        print $item->street; 
        print $item->city;
        print $item->phone; 
    }
    else{
        echo 'No records';
    }
?>

please suggest me where i am wrong

2 Answers 2

1

You do not need to call $item->asXML() since $item is already a SimpleXML object. And you don't have to loop over your array since you can query the necessary agent directly. Try this:

<?php
$xml = simplexml_load_file("note.xml") or die("Error: Cannot create object");
$agent = $xml->xpath('//agent[id=1]');
if (!empty($agent)) {
    $item = $agent[0];
    print $item->id;
    print $item->image;
    print $item->name;
    print $item->company;
    print $item->street;
    print $item->city;
    print $item->phone;
} else {
    echo 'No records';
}
Sign up to request clarification or add additional context in comments.

Comments

1

First of all, you are missing the closing bracket of foreach loop.

Second, you can do this with xPath itself.

Look at this code:

<pre><?php
    $xml = simplexml_load_file("note.xml") or die("Error: Cannot create object");
    $item = $xml->xpath('//agents/agent[id=1]')[0];
    if($item!=null){
        print_r($item);
    }else{
        echo "No Records";
    }
?></pre>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.