0

I have the following php code that I am looking to put into an array, and then json_encode:

$teamQuery = $xpath->query("//td[@align='left']");
$pointsQuery = $xpath->query("//td[@class='sortcell']");

$data = array ();
for($x=1; $x<=30; $x++){
$data[$x]['id'] = $teamQuery->item($x)->nodeValue;
$data[$x]['Team Points'] = $pointsQuery->item($x)->nodeValue;
}

echo json_encode($data);

The output looks like this:

{"1":{"id":"Team Query\n","Points Query":"110"},"

For the purposes of my project I would like to remove the line break (\n), as well as the leading {"1": in the code.

Any help and guidance would be greatly appreciated!

5
  • 1
    i very much doubt your complete output is like this. Commented Apr 2, 2014 at 13:03
  • i condensed it for the purposes of explaining Commented Apr 2, 2014 at 13:04
  • @user3468600 it's misleading and confusing to strip elementary things Commented Apr 2, 2014 at 13:05
  • @DanFromGermany can you elaborate, I'm not sure I follow. I will correct it for next time. Commented Apr 2, 2014 at 13:08
  • your output is an object, because you use an associative array. ($data[$x]) Commented Apr 2, 2014 at 13:45

1 Answer 1

4

I would like to remove the line break (\n)

trim($teamQuery->item($x)->nodeValue)

as well as the leading {"1":

Then don't index your array starting from 1.

Put together:

$data = array();
for ($x = 1; $x <= 30; $x++) {
    $data[] = array(
        'id'          => trim($teamQuery->item($x)->nodeValue),
        'Team Points' => $pointsQuery->item($x)->nodeValue
    );
}
Sign up to request clarification or add additional context in comments.

2 Comments

This worked perfectly. Would you be able to advise as to how I could then echo json_encode($data); into a variable that will plot these values using javascript? I am currently able to do it in two steps: 1. Run the php separately and get the values array 2. take the values from the array and drop them into the javascript variable that is plotting them on a chart. I was hoping that dropping the echo json encode in the variable would work but it doesn't.
<script>var myValues = <?php echo json_encode($data); ?>;</script>

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.